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

/// <summary>
/// 修改优惠券模板状态命令处理器。
/// </summary>
public sealed class ChangeCouponTemplateStatusCommandHandler(
    ICouponRepository couponRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<ChangeCouponTemplateStatusCommand, CouponTemplateDetailDto>
{
    /// <inheritdoc />
    public async Task<CouponTemplateDetailDto> Handle(ChangeCouponTemplateStatusCommand request, CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var template = await couponRepository.FindTemplateByIdAsync(request.TemplateId, tenantId, cancellationToken)
            ?? throw new BusinessException(ErrorCodes.NotFound, "优惠券不存在");

        var scope = CouponTemplateMapping.DeserializeStoreScope(template.StoreScopeJson, template.Id);
        if (!scope.StoreIds.Contains(request.StoreId) && !string.Equals(scope.Mode, "all", StringComparison.Ordinal))
        {
            throw new BusinessException(ErrorCodes.NotFound, "优惠券不存在");
        }

        if (!CouponTemplateMapping.TryParseEditorStatus(request.Status, out var status))
        {
            throw new BusinessException(ErrorCodes.BadRequest, "status 参数不合法");
        }

        template.Status = status;
        await couponRepository.UpdateTemplateAsync(template, cancellationToken);
        await couponRepository.SaveChangesAsync(cancellationToken);

        var channels = CouponTemplateMapping.DeserializeChannels(template.ChannelsJson, template.Id);
        return CouponTemplateDtoFactory.ToDetailDto(template, scope, channels);
    }
}
