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

/// <summary>
/// 删除次卡模板处理器。
/// </summary>
public sealed class DeletePunchCardTemplateCommandHandler(
    IPunchCardRepository repository,
    ITenantProvider tenantProvider)
    : IRequestHandler<DeletePunchCardTemplateCommand>
{
    /// <inheritdoc />
    public async Task Handle(DeletePunchCardTemplateCommand request, CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var entity = await repository.FindTemplateByIdAsync(
            tenantId,
            request.StoreId,
            request.TemplateId,
            cancellationToken)
            ?? throw new BusinessException(ErrorCodes.NotFound, "次卡不存在");

        var aggregate = await repository.GetTemplateAggregateByTemplateIdsAsync(
            tenantId,
            request.StoreId,
            [entity.Id],
            cancellationToken);

        if (aggregate.TryGetValue(entity.Id, out var snapshot) && snapshot.SoldCount > 0)
        {
            throw new BusinessException(ErrorCodes.BadRequest, "已售出的次卡不可删除");
        }

        await repository.DeleteTemplateAsync(entity, cancellationToken);
        await repository.SaveChangesAsync(cancellationToken);
    }
}
