using NSubstitute;
using SIGCM2.Application.Abstractions.Persistence;
using SIGCM2.Application.Roles.List;
using SIGCM2.Domain.Entities;

namespace SIGCM2.Application.Tests.Roles.List;

public class ListRolesQueryHandlerTests
{
    private readonly IRolRepository _repository = Substitute.For<IRolRepository>();
    private readonly ListRolesQueryHandler _handler;

    public ListRolesQueryHandlerTests()
    {
        _handler = new ListRolesQueryHandler(_repository);
    }

    [Fact]
    public async Task Handle_ReturnsAllRolesFromRepositoryAsDtos()
    {
        var now = new DateTime(2026, 4, 15, 10, 0, 0, DateTimeKind.Utc);
        _repository.ListAsync().Returns(new List<Rol>
        {
            new(1, "admin", "Administrador", "Desc admin", true, now, null),
            new(2, "cajero", "Cajero", "Desc cajero", true, now, null),
        });

        var result = await _handler.Handle(new ListRolesQuery());

        Assert.Equal(2, result.Count);
        Assert.Equal("admin", result[0].Codigo);
        Assert.Equal("Administrador", result[0].Nombre);
        Assert.Equal("cajero", result[1].Codigo);
    }

    [Fact]
    public async Task Handle_IncludesInactiveRoles()
    {
        var now = new DateTime(2026, 4, 15, 10, 0, 0, DateTimeKind.Utc);
        _repository.ListAsync().Returns(new List<Rol>
        {
            new(1, "active_code", "Activo", null, true, now, null),
            new(2, "inactive_code", "Inactivo", null, false, now, null),
        });

        var result = await _handler.Handle(new ListRolesQuery());

        Assert.Equal(2, result.Count);
        Assert.True(result[0].Activo);
        Assert.False(result[1].Activo);
    }

    [Fact]
    public async Task Handle_EmptyRepository_ReturnsEmptyList()
    {
        _repository.ListAsync().Returns(new List<Rol>());

        var result = await _handler.Handle(new ListRolesQuery());

        Assert.Empty(result);
    }
}
