using MediatR;
using TakeoutSaaS.Application.App.Billings.Contracts;
using TakeoutSaaS.Application.App.Billings.Queries;
using TakeoutSaaS.Domain.Billings.Repositories;
using TakeoutSaaS.Shared.Abstractions.Results;

namespace TakeoutSaaS.Application.App.Billings.Handlers;

/// <summary>
/// 获取账单列表查询处理器。
/// </summary>
public sealed class ListBillingsQueryHandler(IBillingRepository billingRepository)
    : IRequestHandler<ListBillingsQuery, PagedResult<BillingListDto>>
{
    /// <inheritdoc />
    public async Task<PagedResult<BillingListDto>> Handle(
        ListBillingsQuery request,
        CancellationToken cancellationToken)
    {
        // 1. 查询账单列表
        var (items, totalCount) = await billingRepository.GetListAsync(
            request.TenantId,
            request.Status,
            request.BillingType,
            request.StartDate,
            request.EndDate,
            request.MinAmount,
            request.MaxAmount,
            request.Keyword,
            request.SortBy,
            request.SortDesc,
            request.PageNumber,
            request.PageSize,
            cancellationToken);

        // 2. 映射为 DTO
        var dtos = items.Select(b => new BillingListDto
        {
            Id = b.Id,
            TenantId = b.TenantId,
            TenantName = b.TenantName,
            StatementNo = b.StatementNo,
            BillingType = b.BillingType,
            PeriodStart = b.PeriodStart,
            PeriodEnd = b.PeriodEnd,
            AmountDue = b.AmountDue,
            AmountPaid = b.AmountPaid,
            DiscountAmount = b.DiscountAmount,
            TaxAmount = b.TaxAmount,
            Currency = b.Currency,
            Status = b.Status,
            DueDate = b.DueDate,
            OverdueNotifiedAt = b.OverdueNotifiedAt,
            CreatedAt = b.CreatedAt,
            UpdatedAt = b.UpdatedAt
        }).ToList();

        // 3. 返回分页结果
        return new PagedResult<BillingListDto>(dtos, totalCount, request.PageNumber, request.PageSize);
    }
}
