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 GetFinanceBusinessReportDetailQueryHandler(
    IFinanceBusinessReportRepository financeBusinessReportRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetFinanceBusinessReportDetailQuery, FinanceBusinessReportDetailDto?>
{
    /// <inheritdoc />
    public async Task<FinanceBusinessReportDetailDto?> Handle(
        GetFinanceBusinessReportDetailQuery request,
        CancellationToken cancellationToken)
    {
        // 1. 读取租户上下文并确保成本配置存在。
        var tenantId = tenantProvider.GetCurrentTenantId();
        await financeBusinessReportRepository.EnsureDefaultCostProfilesAsync(
            tenantId,
            request.StoreId,
            cancellationToken);

        // 2. 查询详情（允许实时补算）并映射输出。
        var detail = await financeBusinessReportRepository.GetDetailAsync(
            tenantId,
            request.StoreId,
            request.ReportId,
            allowRealtimeBuild: true,
            cancellationToken);

        return detail is null ? null : FinanceBusinessReportMapping.ToDetail(detail);
    }
}
