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;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Payments.Handlers;

/// <summary>
/// 更新支付记录命令处理器。
/// </summary>
public sealed class UpdatePaymentCommandHandler(
    IPaymentRepository paymentRepository,
    ITenantProvider tenantProvider,
    ILogger<UpdatePaymentCommandHandler> logger)
    : IRequestHandler<UpdatePaymentCommand, PaymentDto?>
{
    private readonly IPaymentRepository _paymentRepository = paymentRepository;
    private readonly ITenantProvider _tenantProvider = tenantProvider;
    private readonly ILogger<UpdatePaymentCommandHandler> _logger = logger;

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

        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;

        await _paymentRepository.UpdatePaymentAsync(existing, cancellationToken);
        await _paymentRepository.SaveChangesAsync(cancellationToken);
        _logger.LogInformation("更新支付记录 {PaymentId}", existing.Id);

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