using MediatR;
using TakeoutSaaS.Application.App.Members.StoredCard.Commands;
using TakeoutSaaS.Domain.Membership.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Members.StoredCard.Handlers;

/// <summary>
/// 删除储值卡方案处理器。
/// </summary>
public sealed class DeleteStoredCardPlanCommandHandler(
    IStoredCardRepository repository,
    ITenantProvider tenantProvider)
    : IRequestHandler<DeleteStoredCardPlanCommand>
{
    /// <inheritdoc />
    public async Task Handle(DeleteStoredCardPlanCommand request, CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();

        var entity = await repository.FindPlanByIdAsync(
            tenantId,
            request.StoreId,
            request.PlanId,
            cancellationToken)
            ?? throw new BusinessException(ErrorCodes.NotFound, "储值卡方案不存在");

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