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

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 获取租户账单列表查询处理器。
/// </summary>
public sealed class GetTenantBillingsQueryHandler(ITenantRepository tenantRepository)
    : IRequestHandler<GetTenantBillingsQuery, PagedResult<TenantBillingListDto>>
{
    /// <inheritdoc />
    public async Task<PagedResult<TenantBillingListDto>> Handle(
        GetTenantBillingsQuery request,
        CancellationToken cancellationToken)
    {
        // 1. 查询租户账单（分页）
        var (billings, totalCount) = await tenantRepository.GetBillingsAsync(
            request.TenantId,
            request.Page,
            request.PageSize,
            cancellationToken);

        // 2. 获取租户名称
        var tenant = await tenantRepository.FindByIdAsync(request.TenantId, cancellationToken);
        var tenantName = tenant?.Name;

        // 3. 映射为 DTO
        var items = billings.Select(b => new TenantBillingListDto
        {
            Id = b.Id,
            TenantId = b.TenantId,
            TenantName = 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();

        // 4. 返回分页结果
        return new PagedResult<TenantBillingListDto>(items, totalCount, request.Page, request.PageSize);
    }
}
