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

/// <summary>
/// 修改限时折扣活动状态命令处理器。
/// </summary>
public sealed class ChangeFlashSaleCampaignStatusCommandHandler(
    IPromotionCampaignRepository promotionCampaignRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<ChangeFlashSaleCampaignStatusCommand, FlashSaleDetailDto>
{
    /// <inheritdoc />
    public async Task<FlashSaleDetailDto> Handle(ChangeFlashSaleCampaignStatusCommand request, CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var campaign = await promotionCampaignRepository.FindByIdAsync(
            request.CampaignId,
            tenantId,
            PromotionType.FlashSale,
            cancellationToken)
            ?? throw new BusinessException(ErrorCodes.NotFound, "活动不存在");

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

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

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

