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

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

/// <summary>
/// 发票记录分页查询处理器。
/// </summary>
public sealed class GetFinanceInvoiceRecordListQueryHandler(
    ITenantInvoiceRepository repository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetFinanceInvoiceRecordListQuery, FinanceInvoiceRecordListResultDto>
{
    /// <inheritdoc />
    public async Task<FinanceInvoiceRecordListResultDto> Handle(
        GetFinanceInvoiceRecordListQuery request,
        CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var keyword = FinanceInvoiceMapping.NormalizeOptionalKeyword(request.Keyword);
        var (startUtc, endUtc) = FinanceInvoiceMapping.NormalizeDateRange(request.StartDateUtc, request.EndDateUtc);
        var page = Math.Max(1, request.Page);
        var pageSize = Math.Clamp(request.PageSize, 1, 200);

        var (items, totalCount) = await repository.SearchRecordsAsync(
            tenantId,
            startUtc,
            endUtc,
            request.Status,
            request.InvoiceType,
            keyword,
            page,
            pageSize,
            cancellationToken);

        var statsSnapshot = await repository.GetStatsAsync(tenantId, DateTime.UtcNow, cancellationToken);

        return new FinanceInvoiceRecordListResultDto
        {
            Items = items.Select(FinanceInvoiceDtoFactory.ToRecordDto).ToList(),
            Page = page,
            PageSize = pageSize,
            TotalCount = totalCount,
            Stats = FinanceInvoiceDtoFactory.ToStatsDto(statsSnapshot)
        };
    }
}
