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

namespace SIGCM2.Application.Tests.Roles.Deactivate;

public class DeactivateRolCommandHandlerTests
{
    private readonly IRolRepository _repository = Substitute.For<IRolRepository>();
    private readonly IAuditLogger _audit = Substitute.For<IAuditLogger>();
    private readonly DeactivateRolCommandHandler _handler;

    private static Rol RolActive(string codigo, int id = 10)
    {
        var now = new DateTime(2026, 4, 15, 10, 0, 0, DateTimeKind.Utc);
        return new Rol(id, codigo, "Nombre", "Desc", true, now, null);
    }

    public DeactivateRolCommandHandlerTests()
    {
        _handler = new DeactivateRolCommandHandler(_repository, _audit);
    }

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

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

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

    [Fact]
    public async Task Handle_CodigoConUsuariosActivos_ThrowsRolInUseException()
    {
        _repository.GetByCodigoAsync("cajero").Returns(RolActive("cajero"));
        _repository.HasActiveUsuariosAsync("cajero").Returns(true);

        var ex = await Assert.ThrowsAsync<RolInUseException>(
            () => _handler.Handle(new DeactivateRolCommand("cajero")));

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

    [Fact]
    public async Task Handle_RolInUse_DoesNotCallUpdateAsync()
    {
        _repository.GetByCodigoAsync("cajero").Returns(RolActive("cajero"));
        _repository.HasActiveUsuariosAsync("cajero").Returns(true);

        try { await _handler.Handle(new DeactivateRolCommand("cajero")); } catch (RolInUseException) { }

        await _repository.DidNotReceive().UpdateAsync(
            Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
    }

    [Fact]
    public async Task Handle_Happy_SetsActivoFalseAndReturnsDto()
    {
        var now = new DateTime(2026, 4, 15, 10, 0, 0, DateTimeKind.Utc);
        var afterDeactivation = new DateTime(2026, 4, 15, 13, 0, 0, DateTimeKind.Utc);

        _repository.GetByCodigoAsync("reportes")
            .Returns(
                RolActive("reportes", 20),
                new Rol(20, "reportes", "Nombre", "Desc", false, now, afterDeactivation));
        _repository.HasActiveUsuariosAsync("reportes").Returns(false);
        _repository.UpdateAsync("reportes", "Nombre", "Desc", false, Arg.Any<CancellationToken>())
            .Returns(true);

        var dto = await _handler.Handle(new DeactivateRolCommand("reportes"));

        Assert.Equal(20, dto.Id);
        Assert.False(dto.Activo);
        Assert.Equal(afterDeactivation, dto.FechaModificacion);
    }

    [Fact]
    public async Task Handle_Happy_CallsUpdateAsyncWithActivoFalse()
    {
        var now = new DateTime(2026, 4, 15, 10, 0, 0, DateTimeKind.Utc);

        _repository.GetByCodigoAsync("reportes")
            .Returns(
                RolActive("reportes"),
                new Rol(10, "reportes", "Nombre", "Desc", false, now, now));
        _repository.HasActiveUsuariosAsync("reportes").Returns(false);
        _repository.UpdateAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
            .Returns(true);

        await _handler.Handle(new DeactivateRolCommand("reportes"));

        await _repository.Received(1).UpdateAsync("reportes", "Nombre", "Desc", false, Arg.Any<CancellationToken>());
    }
}
