using NSubstitute;
using SIGCM2.Application.Abstractions.Persistence;
using SIGCM2.Application.Roles.Get;
using SIGCM2.Domain.Entities;
using SIGCM2.Domain.Exceptions;

namespace SIGCM2.Application.Tests.Roles.Get;

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

    public GetRolByCodigoQueryHandlerTests()
    {
        _handler = new GetRolByCodigoQueryHandler(_repository);
    }

    [Fact]
    public async Task Handle_ExistingCodigo_ReturnsDto()
    {
        var now = new DateTime(2026, 4, 15, 10, 0, 0, DateTimeKind.Utc);
        _repository.GetByCodigoAsync("cajero").Returns(new Rol(5, "cajero", "Cajero", "Desc", true, now, null));

        var dto = await _handler.Handle(new GetRolByCodigoQuery("cajero"));

        Assert.Equal(5, dto.Id);
        Assert.Equal("cajero", dto.Codigo);
        Assert.Equal("Cajero", dto.Nombre);
        Assert.True(dto.Activo);
    }

    [Fact]
    public async Task Handle_NonExistentCodigo_ThrowsRolNotFoundException()
    {
        _repository.GetByCodigoAsync("missing").Returns((Rol?)null);

        var ex = await Assert.ThrowsAsync<RolNotFoundException>(
            () => _handler.Handle(new GetRolByCodigoQuery("missing")));

        Assert.Equal("missing", ex.Codigo);
    }
}
