using FluentValidation;
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using SIGCM2.Application.Abstractions.Persistence;
using SIGCM2.Application.Audit;
using SIGCM2.Application.Common;
using SIGCM2.Application.Usuarios.Update;
using SIGCM2.Domain.Entities;
using SIGCM2.Domain.Exceptions;

namespace SIGCM2.Application.Tests.Usuarios;

public class UpdateUsuarioCommandHandlerTests
{
    private readonly IUsuarioRepository _repo = Substitute.For<IUsuarioRepository>();
    private readonly IRolRepository _rolRepo = Substitute.For<IRolRepository>();
    private readonly IRefreshTokenRepository _refreshRepo = Substitute.For<IRefreshTokenRepository>();
    private readonly IAuditLogger _audit = Substitute.For<IAuditLogger>();
    private readonly UpdateUsuarioCommandHandler _handler;

    public UpdateUsuarioCommandHandlerTests()
    {
        _handler = new UpdateUsuarioCommandHandler(_repo, _rolRepo, _refreshRepo, _audit, TimeProvider.System);

        // Default: rol exists and is active
        _rolRepo.ExistsActiveByCodigoAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(true);
        // Default: 2 active admins (no lockout)
        _repo.CountActiveAdminsAsync(Arg.Any<CancellationToken>()).Returns(2);
    }

    private static Usuario MakeUser(int id = 5, string rol = "cajero", bool activo = true)
        => new(id, "user" + id, "$2a$12$hash", "Test", "User", null, rol, "[]", activo);

    [Fact]
    public async Task Handle_Happy_Path_Updates_And_Returns_Detail()
    {
        var target = MakeUser(5);
        var updated = new Usuario(5, "user5", "$2a$12$hash", "Pedro", "Gómez", "p@g.com", "cajero", "[]", true);

        _repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(target);
        _repo.GetDetailAsync(5, Arg.Any<CancellationToken>()).Returns(updated);

        var cmd = new UpdateUsuarioCommand(5, "Pedro", "Gómez", "p@g.com", "cajero", true);
        var result = await _handler.Handle(cmd);

        Assert.Equal("Pedro", result.Nombre);
        await _repo.Received(1).UpdateAsync(5, Arg.Any<UpdateUsuarioFields>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
    }

    [Fact]
    public async Task Handle_Throws_UsuarioNotFoundException_When_Target_Not_Found()
    {
        _repo.GetByIdAsync(9999, Arg.Any<CancellationToken>()).Returns((Usuario?)null);

        var cmd = new UpdateUsuarioCommand(9999, "A", "B", null, "cajero", true);
        await Assert.ThrowsAsync<UsuarioNotFoundException>(() => _handler.Handle(cmd));
    }

    [Fact]
    public async Task Handle_Throws_LastAdminLockoutException_When_Changing_Role_Of_Last_Admin()
    {
        var lastAdmin = MakeUser(1, "admin", true);
        _repo.GetByIdAsync(1, Arg.Any<CancellationToken>()).Returns(lastAdmin);
        _repo.CountActiveAdminsAsync(Arg.Any<CancellationToken>()).Returns(1);

        var cmd = new UpdateUsuarioCommand(1, "Admin", "Sys", null, "cajero", true); // changing rol
        await Assert.ThrowsAsync<LastAdminLockoutException>(() => _handler.Handle(cmd));
    }

    [Fact]
    public async Task Handle_Throws_LastAdminLockoutException_When_Deactivating_Last_Admin()
    {
        var lastAdmin = MakeUser(1, "admin", true);
        _repo.GetByIdAsync(1, Arg.Any<CancellationToken>()).Returns(lastAdmin);
        _repo.CountActiveAdminsAsync(Arg.Any<CancellationToken>()).Returns(1);

        var cmd = new UpdateUsuarioCommand(1, "Admin", "Sys", null, "admin", false); // activo=false
        await Assert.ThrowsAsync<LastAdminLockoutException>(() => _handler.Handle(cmd));
    }

    [Fact]
    public async Task Handle_Allows_Same_Rol_On_Last_Admin()
    {
        var lastAdmin = MakeUser(1, "admin", true);
        var updatedAdmin = new Usuario(1, "user1", "$2a$12$hash", "Admin", "Sys", null, "admin", "[]", true);

        _repo.GetByIdAsync(1, Arg.Any<CancellationToken>()).Returns(lastAdmin);
        _repo.GetDetailAsync(1, Arg.Any<CancellationToken>()).Returns(updatedAdmin);
        _repo.CountActiveAdminsAsync(Arg.Any<CancellationToken>()).Returns(1);

        var cmd = new UpdateUsuarioCommand(1, "Admin", "Sys", null, "admin", true); // same rol, same activo
        var result = await _handler.Handle(cmd); // should NOT throw

        Assert.NotNull(result);
    }

    [Fact]
    public async Task Handle_Revokes_Refresh_Tokens_On_Role_Change()
    {
        var target = MakeUser(5, "cajero", true);
        var updated = new Usuario(5, "user5", "$2a$12$hash", "Test", "User", null, "admin", "[]", true);

        _repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(target);
        _repo.GetDetailAsync(5, Arg.Any<CancellationToken>()).Returns(updated);

        var cmd = new UpdateUsuarioCommand(5, "Test", "User", null, "admin", true); // rol changed
        await _handler.Handle(cmd);

        await _refreshRepo.Received(1).RevokeAllActiveForUserAsync(5, Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
    }

    [Fact]
    public async Task Handle_Revokes_Refresh_Tokens_When_Deactivating()
    {
        var target = MakeUser(5, "cajero", true);
        var updated = new Usuario(5, "user5", "$2a$12$hash", "Test", "User", null, "cajero", "[]", false);

        _repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(target);
        _repo.GetDetailAsync(5, Arg.Any<CancellationToken>()).Returns(updated);

        var cmd = new UpdateUsuarioCommand(5, "Test", "User", null, "cajero", false); // activo=false
        await _handler.Handle(cmd);

        await _refreshRepo.Received(1).RevokeAllActiveForUserAsync(5, Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
    }

    [Fact]
    public async Task Handle_Does_NOT_Revoke_Tokens_On_Name_Only_Change()
    {
        var target = MakeUser(5, "cajero", true);
        var updated = new Usuario(5, "user5", "$2a$12$hash", "Nuevo", "User", null, "cajero", "[]", true);

        _repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(target);
        _repo.GetDetailAsync(5, Arg.Any<CancellationToken>()).Returns(updated);

        var cmd = new UpdateUsuarioCommand(5, "Nuevo", "User", null, "cajero", true); // only name changed
        await _handler.Handle(cmd);

        await _refreshRepo.DidNotReceive().RevokeAllActiveForUserAsync(Arg.Any<int>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
    }
}
