using MediatR;
using TakeoutSaaS.Application.App.Payments.Dto;
using TakeoutSaaS.Application.App.Payments.Queries;
using TakeoutSaaS.Domain.Payments.Entities;
using TakeoutSaaS.Domain.Payments.Repositories;

namespace TakeoutSaaS.Application.App.Payments.Handlers;

/// <summary>
/// 支付记录详情查询处理器。
/// </summary>
public sealed class GetPaymentByIdQueryHandler(
    IPaymentRepository paymentRepository)
    : IRequestHandler<GetPaymentByIdQuery, PaymentDto?>
{
    /// <inheritdoc />
    public async Task<PaymentDto?> Handle(GetPaymentByIdQuery request, CancellationToken cancellationToken)
    {
        // 1. 查询支付记录（跨租户）
        var payment = await paymentRepository.FindByIdAsync(request.PaymentId, cancellationToken);
        if (payment == null)
        {
            return null;
        }

        // 2. (空行后) 查询退款记录（按支付租户）
        var refunds = await paymentRepository.GetRefundsAsync(payment.Id, payment.TenantId, cancellationToken);
        return MapToDto(payment, refunds);
    }

    private static PaymentDto MapToDto(PaymentRecord payment, IReadOnlyList<PaymentRefundRecord> refunds) => new()
    {
        Id = payment.Id,
        TenantId = payment.TenantId,
        OrderId = payment.OrderId,
        Method = payment.Method,
        Status = payment.Status,
        Amount = payment.Amount,
        TradeNo = payment.TradeNo,
        ChannelTransactionId = payment.ChannelTransactionId,
        PaidAt = payment.PaidAt,
        Remark = payment.Remark,
        Payload = payment.Payload,
        CreatedAt = payment.CreatedAt,
        Refunds = refunds.Select(x => new PaymentRefundDto
        {
            Id = x.Id,
            PaymentRecordId = x.PaymentRecordId,
            OrderId = x.OrderId,
            Amount = x.Amount,
            ChannelRefundId = x.ChannelRefundId,
            Status = x.Status,
            Payload = x.Payload
        }).ToList()
    };
}
