using NSubstitute;
using SIGCM2.Application.Abstractions.Persistence;
using SIGCM2.Application.Common;
using SIGCM2.Application.IngresosBrutos.List;
using SIGCM2.Domain.Fiscal;
using IibbEntity = SIGCM2.Domain.Entities.IngresosBrutos;

namespace SIGCM2.Application.Tests.IngresosBrutos.List;

public class ListIngresosBrutosQueryHandlerTests
{
    private readonly IIngresosBrutosRepository _repo = Substitute.For<IIngresosBrutosRepository>();
    private readonly ListIngresosBrutosQueryHandler _handler;

    private static IibbEntity MakeEntity(int id, ProvinciaArgentina prov) =>
        IibbEntity.FromDb(
            id: id, provincia: prov, descripcion: "IIBB test",
            alicuota: 3m, activo: true,
            vigenciaDesde: new DateOnly(2024, 1, 1),
            vigenciaHasta: null, predecesorId: null,
            fechaCreacion: DateTime.UtcNow, fechaModificacion: null);

    public ListIngresosBrutosQueryHandlerTests()
    {
        _handler = new ListIngresosBrutosQueryHandler(_repo);
    }

    [Fact]
    public async Task Handle_WithItems_ReturnsPagedResultWithMappedDtos()
    {
        var items = new List<IibbEntity>
        {
            MakeEntity(1, ProvinciaArgentina.BuenosAires),
            MakeEntity(2, ProvinciaArgentina.Cordoba),
        };
        _repo.ListAsync(Arg.Any<IngresosBrutosQuery>(), Arg.Any<CancellationToken>())
             .Returns(new PagedResult<IibbEntity>(items, 1, 10, 2));

        var result = await _handler.Handle(new ListIngresosBrutosQuery(1, 10, null, null));

        Assert.Equal(2, result.Items.Count);
        Assert.Equal(2, result.Total);
    }

    [Fact]
    public async Task Handle_PassesProvinciaFilterToRepository()
    {
        _repo.ListAsync(Arg.Any<IngresosBrutosQuery>(), Arg.Any<CancellationToken>())
             .Returns(new PagedResult<IibbEntity>(new List<IibbEntity>(), 1, 10, 0));

        await _handler.Handle(new ListIngresosBrutosQuery(1, 10, true, ProvinciaArgentina.Cordoba));

        await _repo.Received(1).ListAsync(
            Arg.Is<IngresosBrutosQuery>(q => q.Provincia == ProvinciaArgentina.Cordoba && q.Activo == true),
            Arg.Any<CancellationToken>());
    }
}
