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

/// <summary>
/// 秒杀活动详情查询处理器。
/// </summary>
public sealed class GetSeckillCampaignDetailQueryHandler(
    IPromotionCampaignRepository promotionCampaignRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetSeckillCampaignDetailQuery, SeckillDetailDto?>
{
    /// <inheritdoc />
    public async Task<SeckillDetailDto?> Handle(GetSeckillCampaignDetailQuery request, CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var campaign = await promotionCampaignRepository.FindByIdAsync(
            request.CampaignId,
            tenantId,
            PromotionType.Seckill,
            cancellationToken);

        if (campaign is null)
        {
            return null;
        }

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

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


