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

namespace TakeoutSaaS.Application.App.Members.PointsMall.Handlers;

/// <summary>
/// 查询积分商城规则详情处理器。
/// </summary>
public sealed class GetPointMallRuleDetailQueryHandler(
    IPointMallRepository repository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetPointMallRuleDetailQuery, MemberPointMallRuleDetailResultDto>
{
    /// <inheritdoc />
    public async Task<MemberPointMallRuleDetailResultDto> Handle(
        GetPointMallRuleDetailQuery request,
        CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();

        var rule = await repository.GetRuleByStoreAsync(
            tenantId,
            request.StoreId,
            cancellationToken) ?? new MemberPointMallRule
            {
                StoreId = request.StoreId,
                IsConsumeRewardEnabled = true,
                ConsumeAmountPerStep = 1,
                ConsumeRewardPointsPerStep = 1,
                IsReviewRewardEnabled = true,
                ReviewRewardPoints = 10,
                IsRegisterRewardEnabled = true,
                RegisterRewardPoints = 100,
                IsSigninRewardEnabled = false,
                SigninRewardPoints = 5
            };

        var stats = await repository.GetRuleStatsAsync(
            tenantId,
            request.StoreId,
            cancellationToken);

        return new MemberPointMallRuleDetailResultDto
        {
            Rule = MemberPointMallDtoFactory.ToRuleDto(rule),
            Stats = MemberPointMallDtoFactory.ToRuleStatsDto(stats)
        };
    }
}
