using MediatR;
using TakeoutSaaS.Application.App.Coupons.FullReduction.Dto;
using TakeoutSaaS.Application.App.Coupons.FullReduction.Queries;
using TakeoutSaaS.Domain.Coupons.Enums;
using TakeoutSaaS.Domain.Coupons.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Coupons.FullReduction.Handlers;

/// <summary>
/// 满减活动详情查询处理器。
/// </summary>
public sealed class GetFullReductionCampaignDetailQueryHandler(
    IPromotionCampaignRepository promotionCampaignRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetFullReductionCampaignDetailQuery, FullReductionDetailDto?>
{
    /// <inheritdoc />
    public async Task<FullReductionDetailDto?> Handle(GetFullReductionCampaignDetailQuery request, CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var campaign = await promotionCampaignRepository.FindByIdAsync(
            request.CampaignId,
            tenantId,
            PromotionType.FullReduction,
            cancellationToken);

        if (campaign is null)
        {
            return null;
        }

        var rules = FullReductionMapping.DeserializeRules(campaign.RulesJson, campaign.Id);
        if (!rules.StoreIds.Contains(request.OperationStoreId))
        {
            throw new BusinessException(ErrorCodes.NotFound, "活动不存在");
        }

        return FullReductionDtoFactory.ToDetailDto(campaign, rules, DateTime.UtcNow);
    }
}
