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

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 账单分页查询处理器。
/// </summary>
public sealed class SearchTenantBillsQueryHandler(
    ITenantBillingRepository billingRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<SearchTenantBillsQuery, PagedResult<TenantBillingDto>>
{
    /// <summary>
    /// 分页查询账单列表。
    /// </summary>
    /// <param name="request">查询条件。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>分页结果。</returns>
    public async Task<PagedResult<TenantBillingDto>> Handle(SearchTenantBillsQuery 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 bills = await billingRepository.SearchAsync(currentTenantId, request.Status, request.From, request.To, cancellationToken);

        // 4. (空行后) 排序与分页
        var ordered = bills.OrderByDescending(x => x.PeriodEnd).ToList();
        var page = request.Page <= 0 ? 1 : request.Page;
        var size = request.PageSize <= 0 ? 20 : request.PageSize;
        var items = ordered.Skip((page - 1) * size).Take(size).Select(x => x.ToDto()).ToList();

        // 5. (空行后) 返回分页结果
        return new PagedResult<TenantBillingDto>(items, page, size, ordered.Count);
    }
}
