using NSubstitute;
using SIGCM2.Application.Abstractions.Persistence;
using SIGCM2.Application.Common;
using SIGCM2.Application.Secciones.List;
using SIGCM2.Domain.Entities;

namespace SIGCM2.Application.Tests.Secciones.List;

public class ListSeccionesQueryHandlerTests
{
    private readonly ISeccionRepository _repo = Substitute.For<ISeccionRepository>();
    private readonly ListSeccionesQueryHandler _handler;

    public ListSeccionesQueryHandlerTests()
    {
        _handler = new ListSeccionesQueryHandler(_repo);
    }

    private static Seccion MakeSeccion(int id) =>
        new(id, 1, "COD" + id, "Seccion " + id, "clasificados", true, DateTime.UtcNow, null);

    [Fact]
    public async Task Handle_ReturnsPagedDtoItems()
    {
        var items = new List<Seccion> { MakeSeccion(1), MakeSeccion(2) };
        var pagedResult = new PagedResult<Seccion>(items, 1, 20, 2);

        _repo.GetPagedAsync(Arg.Any<SeccionesQuery>(), Arg.Any<CancellationToken>())
            .Returns(pagedResult);

        var query = new ListSeccionesQuery(1, 20, null, null, null, null);
        var result = await _handler.Handle(query);

        Assert.Equal(2, result.Total);
        Assert.Equal(2, result.Items.Count);
        Assert.Equal("COD1", result.Items[0].Codigo);
    }

    [Fact]
    public async Task Handle_ClampsPageSizeToMax100()
    {
        _repo.GetPagedAsync(Arg.Any<SeccionesQuery>(), Arg.Any<CancellationToken>())
            .Returns(new PagedResult<Seccion>([], 1, 100, 0));

        await _handler.Handle(new ListSeccionesQuery(1, 500, null, null, null, null));

        await _repo.Received(1).GetPagedAsync(
            Arg.Is<SeccionesQuery>(q => q.PageSize == 100),
            Arg.Any<CancellationToken>());
    }

    [Fact]
    public async Task Handle_ClampsPageToMin1()
    {
        _repo.GetPagedAsync(Arg.Any<SeccionesQuery>(), Arg.Any<CancellationToken>())
            .Returns(new PagedResult<Seccion>([], 1, 20, 0));

        await _handler.Handle(new ListSeccionesQuery(0, 20, null, null, null, null));

        await _repo.Received(1).GetPagedAsync(
            Arg.Is<SeccionesQuery>(q => q.Page == 1),
            Arg.Any<CancellationToken>());
    }
}
