using SIGCM2.Application.Abstractions;
using SIGCM2.Application.Abstractions.Persistence;
using SIGCM2.Application.Common;
using SIGCM2.Application.Pricing.ChargeableChars;
using SIGCM2.Domain.Pricing.ChargeableChars;

namespace SIGCM2.Application.Pricing.ChargeableChars.List;

/// <summary>
/// PRC-001 — Handler for ListChargeableCharConfigQuery.
/// Projects ChargeableCharConfig entities to ChargeableCharConfigDto.
/// </summary>
public sealed class ListChargeableCharConfigQueryHandler
    : ICommandHandler<ListChargeableCharConfigQuery, PagedResult<ChargeableCharConfigDto>>
{
    private readonly IChargeableCharConfigRepository _repo;

    public ListChargeableCharConfigQueryHandler(IChargeableCharConfigRepository repo)
    {
        _repo = repo;
    }

    public async Task<PagedResult<ChargeableCharConfigDto>> Handle(ListChargeableCharConfigQuery query)
    {
        var page     = Math.Max(1, query.Page);
        var pageSize = Math.Clamp(query.PageSize, 1, 100);
        var skip     = (page - 1) * pageSize;

        var items = await _repo.ListAsync(query.ProductTypeId, query.ActiveOnly, skip, pageSize);
        var total = await _repo.CountAsync(query.ProductTypeId, query.ActiveOnly);

        var dtos = items.Select(ToDto).ToList();

        return new PagedResult<ChargeableCharConfigDto>(dtos, page, pageSize, total);
    }

    private static ChargeableCharConfigDto ToDto(ChargeableCharConfig c) => new(
        c.Id,
        c.ProductTypeId,
        c.Symbol,
        c.Category,
        c.PricePerUnit,
        c.ValidFrom,
        c.ValidTo,
        c.IsActive);
}
