using MediatR;
using TakeoutSaaS.Application.App.Billings.Commands;
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 CancelBillingCommandHandler(
    ITenantBillingRepository billingRepository)
    : IRequestHandler<CancelBillingCommand, Unit>
{
    /// <inheritdoc />
    public async Task<Unit> Handle(CancelBillingCommand request, CancellationToken cancellationToken)
    {
        // 1. 查询账单
        var billing = await billingRepository.FindByIdAsync(request.BillingId, cancellationToken);
        if (billing is null)
        {
            throw new BusinessException(ErrorCodes.NotFound, "账单不存在");
        }

        // 2. 取消账单（领域规则校验在实体方法内）
        billing.Cancel(request.Reason);

        // 3. 持久化
        await billingRepository.UpdateAsync(billing, cancellationToken);
        await billingRepository.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}

