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

namespace TakeoutSaaS.Application.App.Billings.Handlers;

/// <summary>
/// 更新账单状态处理器。
/// </summary>
public sealed class UpdateBillStatusCommandHandler(
    ITenantBillingRepository billingRepository,
    ITenantRepository tenantRepository)
    : IRequestHandler<UpdateBillStatusCommand, BillDto?>
{
    /// <summary>
    /// 处理更新账单状态请求。
    /// </summary>
    /// <param name="request">更新命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>账单 DTO 或 null。</returns>
    public async Task<BillDto?> Handle(UpdateBillStatusCommand request, CancellationToken cancellationToken)
    {
        // 1. 查询账单
        var bill = await billingRepository.FindByIdAsync(request.BillId, cancellationToken);
        if (bill is null)
        {
            return null;
        }

        // 2. 更新状态
        bill.Status = request.Status;
        if (!string.IsNullOrWhiteSpace(request.Notes))
        {
            bill.LineItemsJson = request.Notes;
        }

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

        // 4. 查询租户名称
        var tenant = await tenantRepository.FindByIdAsync(bill.TenantId, cancellationToken);

        // 5. 返回 DTO
        return bill.ToDto(tenant?.Name);
    }
}
