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

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

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

        var status = FullReductionMapping.ParseStatus(request.Status);
        campaign.Status = status;

        if (status == PromotionStatus.Completed)
        {
            var nowUtc = DateTime.UtcNow;
            if (campaign.EndAt > nowUtc)
            {
                campaign.EndAt = nowUtc;
            }
        }

        await promotionCampaignRepository.UpdateAsync(campaign, cancellationToken);
        await promotionCampaignRepository.SaveChangesAsync(cancellationToken);

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