using MediatR;
using TakeoutSaaS.Application.App.Finance.Reports.Dto;
using TakeoutSaaS.Application.App.Finance.Reports.Queries;
using TakeoutSaaS.Domain.Finance.Repositories;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Finance.Reports.Handlers;

/// <summary>
/// 经营报表分页查询处理器。
/// </summary>
public sealed class SearchFinanceBusinessReportListQueryHandler(
    IFinanceBusinessReportRepository financeBusinessReportRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<SearchFinanceBusinessReportListQuery, FinanceBusinessReportListResultDto>
{
    /// <inheritdoc />
    public async Task<FinanceBusinessReportListResultDto> Handle(
        SearchFinanceBusinessReportListQuery request,
        CancellationToken cancellationToken)
    {
        // 1. 读取租户上下文并归一化分页参数。
        var tenantId = tenantProvider.GetCurrentTenantId();
        var normalizedPage = Math.Max(1, request.Page);
        var normalizedPageSize = Math.Clamp(request.PageSize, 1, 200);

        // 2. 确保成本配置并补齐分页周期快照。
        await financeBusinessReportRepository.EnsureDefaultCostProfilesAsync(
            tenantId,
            request.StoreId,
            cancellationToken);
        await financeBusinessReportRepository.QueueSnapshotsForPageAsync(
            tenantId,
            request.StoreId,
            request.PeriodType,
            normalizedPage,
            normalizedPageSize,
            cancellationToken);

        // 3. 查询分页快照并映射输出。
        var pageSnapshot = await financeBusinessReportRepository.SearchPageAsync(
            tenantId,
            request.StoreId,
            request.PeriodType,
            normalizedPage,
            normalizedPageSize,
            cancellationToken);

        return new FinanceBusinessReportListResultDto
        {
            Items = pageSnapshot.Items.Select(FinanceBusinessReportMapping.ToListItem).ToList(),
            Total = pageSnapshot.TotalCount,
            Page = normalizedPage,
            PageSize = normalizedPageSize
        };
    }
}
