using MediatR;
using TakeoutSaaS.Application.App.Coupons.Seckill.Commands;
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 DeleteSeckillCampaignCommandHandler(
    IPromotionCampaignRepository promotionCampaignRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<DeleteSeckillCampaignCommand, Unit>
{
    /// <inheritdoc />
    public async Task<Unit> Handle(DeleteSeckillCampaignCommand request, CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var campaign = await promotionCampaignRepository.FindByIdAsync(
            request.CampaignId,
            tenantId,
            PromotionType.Seckill,
            cancellationToken)
            ?? throw new BusinessException(ErrorCodes.NotFound, "活动不存在");

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

        await promotionCampaignRepository.DeleteAsync(campaign, cancellationToken);
        await promotionCampaignRepository.SaveChangesAsync(cancellationToken);
        return Unit.Value;
    }
}


