using MediatR;
using TakeoutSaaS.Application.App.Members.Dto;
using TakeoutSaaS.Application.App.Members.Queries;
using TakeoutSaaS.Domain.Membership.Repositories;
using TakeoutSaaS.Domain.Orders.Repositories;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Members.Handlers;

/// <summary>
/// 会员日配置查询处理器。
/// </summary>
public sealed class GetMemberDaySettingQueryHandler(
    IMemberRepository memberRepository,
    IOrderRepository orderRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetMemberDaySettingQuery, MemberDaySettingDto>
{
    /// <inheritdoc />
    public async Task<MemberDaySettingDto> Handle(GetMemberDaySettingQuery request, CancellationToken cancellationToken)
    {
        await MemberCenterSupport.EnsureMemberCenterInitializedAsync(
            memberRepository,
            orderRepository,
            tenantProvider,
            cancellationToken);

        var tenantId = tenantProvider.GetCurrentTenantId();
        var setting = await memberRepository.GetMemberDaySettingAsync(tenantId, cancellationToken);
        if (setting is null)
        {
            return new MemberDaySettingDto
            {
                IsEnabled = true,
                Weekday = 2,
                ExtraDiscountRate = 9m
            };
        }

        return MemberCenterSupport.ToMemberDaySettingDto(setting);
    }
}
