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

namespace TakeoutSaaS.Application.App.Payments.Handlers;

/// <summary>
/// 删除支付记录命令处理器。
/// </summary>
public sealed class DeletePaymentCommandHandler(
    IPaymentRepository paymentRepository,
    ILogger<DeletePaymentCommandHandler> logger)
    : IRequestHandler<DeletePaymentCommand, bool>
{
    /// <inheritdoc />
    public async Task<bool> Handle(DeletePaymentCommand request, CancellationToken cancellationToken)
    {
        // 1. 查询支付记录（跨租户）
        var existing = await paymentRepository.FindByIdAsync(request.PaymentId, cancellationToken);
        if (existing == null)
        {
            return false;
        }

        // 2. (空行后) 删除并持久化（按支付租户）
        await paymentRepository.DeletePaymentAsync(request.PaymentId, existing.TenantId, cancellationToken);
        await paymentRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("删除支付记录 {PaymentId}", request.PaymentId);

        return true;
    }
}
