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

namespace TakeoutSaaS.Application.App.Payments.Handlers;

/// <summary>
/// 支付记录详情查询处理器。
/// </summary>
public sealed class GetPaymentByIdQueryHandler(
    IPaymentRepository paymentRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetPaymentByIdQuery, PaymentDto?>
{
    private readonly IPaymentRepository _paymentRepository = paymentRepository;
    private readonly ITenantProvider _tenantProvider = tenantProvider;

    /// <inheritdoc />
    public async Task<PaymentDto?> Handle(GetPaymentByIdQuery request, CancellationToken cancellationToken)
    {
        var tenantId = _tenantProvider.GetCurrentTenantId();
        var payment = await _paymentRepository.FindByIdAsync(request.PaymentId, tenantId, cancellationToken);
        if (payment == null)
        {
            return null;
        }

        var refunds = await _paymentRepository.GetRefundsAsync(payment.Id, 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()
    };
}
