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 UpdatePaymentCommandHandler(
    IPaymentRepository paymentRepository,
    ILogger<UpdatePaymentCommandHandler> logger)
    : IRequestHandler<UpdatePaymentCommand, PaymentDto?>
{
    /// <inheritdoc />
    public async Task<PaymentDto?> Handle(UpdatePaymentCommand request, CancellationToken cancellationToken)
    {
        // 1. 查询支付记录（跨租户）
        var existing = await paymentRepository.FindByIdAsync(request.PaymentId, cancellationToken);
        if (existing == null)
        {
            return null;
        }

        // 2. (空行后) 更新字段
        existing.OrderId = request.OrderId;
        existing.Method = request.Method;
        existing.Status = request.Status;
        existing.Amount = request.Amount;
        existing.TradeNo = request.TradeNo?.Trim();
        existing.ChannelTransactionId = request.ChannelTransactionId?.Trim();
        existing.PaidAt = request.PaidAt;
        existing.Remark = request.Remark?.Trim();
        existing.Payload = request.Payload;

        // 3. (空行后) 持久化
        await paymentRepository.UpdatePaymentAsync(existing, cancellationToken);
        await paymentRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("更新支付记录 {PaymentId}", existing.Id);

        // 4. (空行后) 查询退款记录并返回
        var refunds = await paymentRepository.GetRefundsAsync(existing.Id, existing.TenantId, cancellationToken);
        return MapToDto(existing, 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()
    };
}
