using MediatR;
using TakeoutSaaS.Application.App.Tenants.Dto;
using TakeoutSaaS.Application.App.Tenants.Queries;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 账单详情查询处理器。
/// </summary>
public sealed class GetTenantBillQueryHandler(
    ITenantBillingRepository billingRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetTenantBillQuery, TenantBillingDto?>
{
    /// <summary>
    /// 查询账单详情。
    /// </summary>
    /// <param name="request">查询请求。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>账单 DTO 或 null。</returns>
    public async Task<TenantBillingDto?> Handle(GetTenantBillQuery request, CancellationToken cancellationToken)
    {
        // 1. 校验租户上下文（租户端禁止跨租户）
        var currentTenantId = tenantProvider.GetCurrentTenantId();
        if (currentTenantId <= 0)
        {
            throw new BusinessException(ErrorCodes.BadRequest, "缺少租户标识");
        }

        // 2. (空行后) 兼容旧调用：若传入 TenantId，则必须与当前租户一致
        if (request.TenantId > 0 && request.TenantId != currentTenantId)
        {
            throw new BusinessException(ErrorCodes.Forbidden, "无权查询其他租户账单");
        }

        // 3. (空行后) 查询账单
        var bill = await billingRepository.FindByIdAsync(currentTenantId, request.BillingId, cancellationToken);

        // 4. (空行后) 返回 DTO 或 null
        return bill?.ToDto();
    }
}
