using MediatR;
using TakeoutSaaS.Application.App.Billings.Commands;
using TakeoutSaaS.Application.App.Billings.Dto;
using TakeoutSaaS.Domain.Tenants.Entities;
using TakeoutSaaS.Domain.Tenants.Enums;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Ids;

namespace TakeoutSaaS.Application.App.Billings.Handlers;

/// <summary>
/// 记录支付处理器。
/// </summary>
public sealed class RecordPaymentCommandHandler(
    ITenantBillingRepository billingRepository,
    ITenantPaymentRepository paymentRepository,
    IIdGenerator idGenerator)
    : IRequestHandler<RecordPaymentCommand, PaymentRecordDto>
{
    /// <summary>
    /// 处理记录支付请求。
    /// </summary>
    /// <param name="request">记录支付命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>支付 DTO。</returns>
    public async Task<PaymentRecordDto> Handle(RecordPaymentCommand request, CancellationToken cancellationToken)
    {
        // 1. 查询账单
        var billing = await billingRepository.FindByIdAsync(request.BillingId, cancellationToken);
        if (billing is null)
        {
            throw new BusinessException(ErrorCodes.NotFound, "账单不存在");
        }

        // 2. 业务规则检查
        if (billing.Status == TenantBillingStatus.Paid)
        {
            throw new BusinessException(ErrorCodes.BusinessError, "已支付账单不允许重复收款");
        }

        if (billing.Status == TenantBillingStatus.Cancelled)
        {
            throw new BusinessException(ErrorCodes.BusinessError, "已取消账单不允许收款");
        }

        // 3. 幂等校验：交易号唯一
        if (!string.IsNullOrWhiteSpace(request.TransactionNo))
        {
            var exists = await paymentRepository.GetByTransactionNoAsync(request.TransactionNo.Trim(), cancellationToken);
            if (exists is not null)
            {
                throw new BusinessException(ErrorCodes.Conflict, "交易号已存在，疑似重复提交");
            }
        }

        // 4. 构建支付记录（默认待审核）
        var now = DateTime.UtcNow;
        var payment = new TenantPayment
        {
            Id = idGenerator.NextId(),
            TenantId = billing.TenantId,
            BillingStatementId = request.BillingId,
            Amount = request.Amount,
            Method = request.Method,
            Status = TenantPaymentStatus.Pending,
            TransactionNo = string.IsNullOrWhiteSpace(request.TransactionNo) ? null : request.TransactionNo.Trim(),
            ProofUrl = request.ProofUrl,
            PaidAt = now,
            Notes = request.Notes
        };

        // 5. 持久化变更
        await paymentRepository.AddAsync(payment, cancellationToken);
        await paymentRepository.SaveChangesAsync(cancellationToken);

        // 6. 返回 DTO
        return payment.ToPaymentRecordDto();
    }
}
