using NSubstitute;
using SIGCM2.Application.Abstractions.Persistence;
using SIGCM2.Application.TiposDeIva.GetHistorial;
using SIGCM2.Domain.Entities;

namespace SIGCM2.Application.Tests.TiposDeIva.GetHistorial;

public class GetHistorialTipoDeIvaQueryHandlerTests
{
    private readonly ITipoDeIvaRepository _repo = Substitute.For<ITipoDeIvaRepository>();
    private readonly GetHistorialTipoDeIvaQueryHandler _handler;

    public GetHistorialTipoDeIvaQueryHandlerTests()
    {
        _handler = new GetHistorialTipoDeIvaQueryHandler(_repo);
    }

    private static TipoDeIva MakeEntity(int id, int? predecesorId, DateOnly desde) =>
        TipoDeIva.FromDb(id, "IVA_21", "IVA 21%", 21m, true, true, desde,
            predecesorId.HasValue ? desde.AddYears(1).AddDays(-1) : null,
            predecesorId, DateTime.UtcNow, null);

    [Fact]
    public async Task Handle_ChainOf3_ReturnsListWith3ItemsInOrder()
    {
        var chain = new List<TipoDeIva>
        {
            MakeEntity(1, null, new DateOnly(2022, 1, 1)),
            MakeEntity(2, 1,    new DateOnly(2023, 1, 1)),
            MakeEntity(3, 2,    new DateOnly(2024, 1, 1)),
        };
        _repo.GetHistorialAsync(3, Arg.Any<CancellationToken>()).Returns(chain);

        var result = await _handler.Handle(new GetHistorialTipoDeIvaQuery(3));

        Assert.Equal(3, result.Count);
        Assert.Equal(1, result[0].Version);  // root
        Assert.Equal(3, result[2].Version);  // current
    }

    [Fact]
    public async Task Handle_SingleVersion_Returns1Item()
    {
        var chain = new List<TipoDeIva> { MakeEntity(1, null, new DateOnly(2024, 1, 1)) };
        _repo.GetHistorialAsync(1, Arg.Any<CancellationToken>()).Returns(chain);

        var result = await _handler.Handle(new GetHistorialTipoDeIvaQuery(1));

        Assert.Single(result);
        Assert.Equal(1, result[0].Version);
    }
}
