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 GetFinanceCostEntryQueryHandler(
    IFinanceCostRepository financeCostRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetFinanceCostEntryQuery, FinanceCostEntryDto>
{
    /// <inheritdoc />
    public async Task<FinanceCostEntryDto> Handle(
        GetFinanceCostEntryQuery request,
        CancellationToken cancellationToken)
    {
        // 1. 读取租户上下文并查询月度快照。
        var tenantId = tenantProvider.GetCurrentTenantId();
        var normalizedMonth = FinanceCostMapping.NormalizeMonthStart(request.CostMonth);
        var snapshot = await financeCostRepository.GetMonthSnapshotAsync(
            tenantId,
            request.Dimension,
            request.StoreId,
            normalizedMonth,
            cancellationToken);

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