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

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

/// <summary>
/// 成本分析查询处理器。
/// </summary>
public sealed class GetFinanceCostAnalysisQueryHandler(
    IFinanceCostRepository financeCostRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetFinanceCostAnalysisQuery, FinanceCostAnalysisDto>
{
    /// <inheritdoc />
    public async Task<FinanceCostAnalysisDto> Handle(
        GetFinanceCostAnalysisQuery request,
        CancellationToken cancellationToken)
    {
        // 1. 读取租户上下文并查询分析快照。
        var tenantId = tenantProvider.GetCurrentTenantId();
        var normalizedMonth = FinanceCostMapping.NormalizeMonthStart(request.CostMonth);
        var snapshot = await financeCostRepository.GetAnalysisSnapshotAsync(
            tenantId,
            request.Dimension,
            request.StoreId,
            normalizedMonth,
            request.TrendMonthCount,
            cancellationToken);

        // 2. 映射 DTO 返回。
        return FinanceCostMapping.ToAnalysisDto(snapshot);
    }
}
