using MediatR;
using TakeoutSaaS.Application.App.Coupons.Seckill.Commands;
using TakeoutSaaS.Application.App.Coupons.Seckill.Dto;
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 ChangeSeckillCampaignStatusCommandHandler(
    IPromotionCampaignRepository promotionCampaignRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<ChangeSeckillCampaignStatusCommand, SeckillDetailDto>
{
    /// <inheritdoc />
    public async Task<SeckillDetailDto> Handle(ChangeSeckillCampaignStatusCommand 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, "活动不存在");
        }

        campaign.Status = SeckillMapping.ParseStatus(request.Status);

        await promotionCampaignRepository.UpdateAsync(campaign, cancellationToken);
        await promotionCampaignRepository.SaveChangesAsync(cancellationToken);
        return SeckillDtoFactory.ToDetailDto(campaign, rules, DateTime.UtcNow);
    }
}


