using MediatR;
using TakeoutSaaS.Application.App.Tenants.Commands;
using TakeoutSaaS.Application.App.Tenants.Dto;
using TakeoutSaaS.Domain.Tenants.Enums;
using TakeoutSaaS.Domain.Tenants.Repositories;

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 标记账单支付处理器。
/// </summary>
public sealed class MarkTenantBillingPaidCommandHandler(ITenantBillingRepository billingRepository)
    : IRequestHandler<MarkTenantBillingPaidCommand, TenantBillingDto?>
{
    /// <summary>
    /// 标记账单支付。
    /// </summary>
    /// <param name="request">标记命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>账单 DTO 或 null。</returns>
    public async Task<TenantBillingDto?> Handle(MarkTenantBillingPaidCommand request, CancellationToken cancellationToken)
    {
        // 1. 查询账单
        var bill = await billingRepository.FindByIdAsync(request.TenantId, request.BillingId, cancellationToken);
        if (bill == null)
        {
            return null;
        }

        // 2. 更新支付状态
        bill.AmountPaid = request.AmountPaid;
        bill.Status = TenantBillingStatus.Paid;
        bill.DueDate = bill.DueDate;

        // 3. 持久化变更
        await billingRepository.UpdateAsync(bill, cancellationToken);
        await billingRepository.SaveChangesAsync(cancellationToken);

        // 4. 返回 DTO
        return bill.ToDto();
    }
}
