using MediatR;
using TakeoutSaaS.Application.App.Coupons.Commands;
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 DeleteCouponTemplateCommandHandler(
    ICouponRepository couponRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<DeleteCouponTemplateCommand, Unit>
{
    /// <inheritdoc />
    public async Task<Unit> Handle(DeleteCouponTemplateCommand 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 (template.ClaimedQuantity > 0)
        {
            throw new BusinessException(ErrorCodes.Conflict, "优惠券已被领取，禁止删除");
        }

        var issuedCount = await couponRepository.CountIssuedCouponsByTemplateIdAsync(tenantId, template.Id, cancellationToken);
        if (issuedCount > 0)
        {
            throw new BusinessException(ErrorCodes.Conflict, "优惠券已被领取，禁止删除");
        }

        await couponRepository.DeleteTemplateAsync(template, cancellationToken);
        await couponRepository.SaveChangesAsync(cancellationToken);
        return Unit.Value;
    }
}
