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

namespace TakeoutSaaS.Application.App.Payments.Handlers;

/// <summary>
/// 创建支付记录命令处理器。
/// </summary>
public sealed class CreatePaymentCommandHandler(IPaymentRepository paymentRepository, ILogger<CreatePaymentCommandHandler> logger)
    : IRequestHandler<CreatePaymentCommand, PaymentDto>
{
    private readonly IPaymentRepository _paymentRepository = paymentRepository;
    private readonly ILogger<CreatePaymentCommandHandler> _logger = logger;

    /// <inheritdoc />
    public async Task<PaymentDto> Handle(CreatePaymentCommand request, CancellationToken cancellationToken)
    {
        var payment = new PaymentRecord
        {
            OrderId = request.OrderId,
            Method = request.Method,
            Status = request.Status,
            Amount = request.Amount,
            TradeNo = request.TradeNo?.Trim(),
            ChannelTransactionId = request.ChannelTransactionId?.Trim(),
            PaidAt = request.PaidAt,
            Remark = request.Remark?.Trim(),
            Payload = request.Payload
        };

        await _paymentRepository.AddPaymentAsync(payment, cancellationToken);
        await _paymentRepository.SaveChangesAsync(cancellationToken);
        _logger.LogInformation("创建支付记录 {PaymentId} 对应订单 {OrderId}", payment.Id, payment.OrderId);

        return MapToDto(payment, []);
    }

    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()
    };
}
