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

namespace SIGCM2.Application.Tests.PuntosDeVenta.List;

public class ListPuntosDeVentaQueryHandlerTests
{
    private readonly IPuntoDeVentaRepository _repo = Substitute.For<IPuntoDeVentaRepository>();
    private readonly ListPuntosDeVentaQueryHandler _handler;

    public ListPuntosDeVentaQueryHandlerTests()
    {
        _handler = new ListPuntosDeVentaQueryHandler(_repo);
    }

    private static PuntoDeVenta MakePdv(int id) =>
        new(id, 5, (short)id, "PdV " + id, null, true, DateTime.UtcNow, null);

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

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

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

        Assert.Equal(2, result.Total);
        Assert.Equal(2, result.Items.Count);
        Assert.Equal(1, result.Items[0].NumeroAFIP);
    }

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

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

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

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

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

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

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

        await _handler.Handle(new ListPuntosDeVentaQuery(1, 20, MedioId: 5, null));

        await _repo.Received(1).GetPagedAsync(
            Arg.Is<PuntosDeVentaQuery>(q => q.MedioId == 5),
            Arg.Any<CancellationToken>());
    }
}
