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

namespace SIGCM2.Application.Tests.Medios.List;

public class ListMediosQueryHandlerTests
{
    private readonly IMedioRepository _repo = Substitute.For<IMedioRepository>();
    private readonly ListMediosQueryHandler _handler;

    public ListMediosQueryHandlerTests()
    {
        _handler = new ListMediosQueryHandler(_repo);
    }

    private static Medio MakeMedio(int id) =>
        new(id, "COD" + id, "Medio " + id, TipoMedio.Diario, null, true, DateTime.UtcNow, null);

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

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

        var query = new ListMediosQuery(1, 20, 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);
        Assert.Equal("COD2", result.Items[1].Codigo);
    }

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

        await _handler.Handle(new ListMediosQuery(1, 999, null, null, null));

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

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

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

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