using MediatR;
using TakeoutSaaS.Application.App.Billings.Commands;
using TakeoutSaaS.Domain.Tenants.Enums;
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 UpdateBillingStatusCommandHandler(
    ITenantBillingRepository billingRepository)
    : IRequestHandler<UpdateBillingStatusCommand, Unit>
{
    /// <inheritdoc />
    public async Task<Unit> Handle(UpdateBillingStatusCommand 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 && request.NewStatus != TenantBillingStatus.Paid)
        {
            throw new BusinessException(ErrorCodes.BusinessError, "已支付账单不允许改为其他状态");
        }

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

        // 3. 更新状态与备注
        billing.Status = request.NewStatus;
        if (!string.IsNullOrWhiteSpace(request.Notes))
        {
            billing.Notes = string.IsNullOrWhiteSpace(billing.Notes)
                ? $"[状态变更] {request.Notes}"
                : $"{billing.Notes}\n[状态变更] {request.Notes}";
        }

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

        return Unit.Value;
    }
}

