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

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

/// <summary>
/// 财务概览查询处理器。
/// </summary>
public sealed class GetFinanceOverviewDashboardQueryHandler(
    IFinanceOverviewRepository financeOverviewRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetFinanceOverviewDashboardQuery, FinanceOverviewDashboardDto>
{
    /// <inheritdoc />
    public async Task<FinanceOverviewDashboardDto> Handle(
        GetFinanceOverviewDashboardQuery request,
        CancellationToken cancellationToken)
    {
        // 1. 拉取租户上下文并读取快照。
        var tenantId = tenantProvider.GetCurrentTenantId();
        var snapshot = await financeOverviewRepository.GetDashboardSnapshotAsync(
            tenantId,
            request.Dimension,
            request.StoreId,
            request.CurrentUtc,
            cancellationToken);

        // 2. 映射页面 DTO。
        return FinanceOverviewMapping.ToDashboardDto(snapshot);
    }
}
