using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Payments.Commands;
using TakeoutSaaS.Application.App.Payments.Dto;
using TakeoutSaaS.Domain.Orders.Repositories;
using TakeoutSaaS.Domain.Payments.Entities;
using TakeoutSaaS.Domain.Payments.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;

namespace TakeoutSaaS.Application.App.Payments.Handlers;

/// <summary>
/// 创建支付记录命令处理器。
/// </summary>
public sealed class CreatePaymentCommandHandler(
    IPaymentRepository paymentRepository,
    IOrderRepository orderRepository,
    ILogger<CreatePaymentCommandHandler> logger)
    : IRequestHandler<CreatePaymentCommand, PaymentDto>
{
    /// <inheritdoc />
    public async Task<PaymentDto> Handle(CreatePaymentCommand request, CancellationToken cancellationToken)
    {
        // 1. 查询订单以确定租户
        var order = await orderRepository.FindByIdAsync(request.OrderId, cancellationToken);
        if (order is null)
        {
            throw new BusinessException(ErrorCodes.NotFound, "订单不存在");
        }

        // 2. (空行后) 构建支付记录并写入租户
        var payment = new PaymentRecord
        {
            TenantId = order.TenantId,
            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
        };

        // 3. (空行后) 持久化
        await paymentRepository.AddPaymentAsync(payment, cancellationToken);
        await paymentRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("创建支付记录 {PaymentId} 对应订单 {OrderId}", payment.Id, payment.OrderId);

        // 4. (空行后) 返回 DTO
        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()
    };
}
