using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Payments.Commands;
using TakeoutSaaS.Domain.Payments.Repositories;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Payments.Handlers;

/// <summary>
/// 删除支付记录命令处理器。
/// </summary>
public sealed class DeletePaymentCommandHandler(
    IPaymentRepository paymentRepository,
    ITenantProvider tenantProvider,
    ILogger<DeletePaymentCommandHandler> logger)
    : IRequestHandler<DeletePaymentCommand, bool>
{
    private readonly IPaymentRepository _paymentRepository = paymentRepository;
    private readonly ITenantProvider _tenantProvider = tenantProvider;
    private readonly ILogger<DeletePaymentCommandHandler> _logger = logger;

    /// <inheritdoc />
    public async Task<bool> Handle(DeletePaymentCommand request, CancellationToken cancellationToken)
    {
        var tenantId = _tenantProvider.GetCurrentTenantId();
        var existing = await _paymentRepository.FindByIdAsync(request.PaymentId, tenantId, cancellationToken);
        if (existing == null)
        {
            return false;
        }

        await _paymentRepository.DeletePaymentAsync(request.PaymentId, tenantId, cancellationToken);
        await _paymentRepository.SaveChangesAsync(cancellationToken);
        _logger.LogInformation("删除支付记录 {PaymentId}", request.PaymentId);

        return true;
    }
}
