using MediatR;
using TakeoutSaaS.Application.App.Coupons.FlashSale.Dto;
using TakeoutSaaS.Application.App.Coupons.FlashSale.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.FlashSale.Handlers;

/// <summary>
/// 限时折扣活动详情查询处理器。
/// </summary>
public sealed class GetFlashSaleCampaignDetailQueryHandler(
    IPromotionCampaignRepository promotionCampaignRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetFlashSaleCampaignDetailQuery, FlashSaleDetailDto?>
{
    /// <inheritdoc />
    public async Task<FlashSaleDetailDto?> Handle(GetFlashSaleCampaignDetailQuery request, CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var campaign = await promotionCampaignRepository.FindByIdAsync(
            request.CampaignId,
            tenantId,
            PromotionType.FlashSale,
            cancellationToken);

        if (campaign is null)
        {
            return null;
        }

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

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

