using NSubstitute;
using SIGCM2.Application.Abstractions.Persistence;
using SIGCM2.Application.Audit;
using SIGCM2.Application.Common;
using SIGCM2.Application.Usuarios.Reactivate;
using SIGCM2.Domain.Entities;
using SIGCM2.Domain.Exceptions;

namespace SIGCM2.Application.Tests.Usuarios;

public class ReactivateUsuarioCommandHandlerTests
{
    private readonly IUsuarioRepository _repo = Substitute.For<IUsuarioRepository>();
    private readonly IAuditLogger _audit = Substitute.For<IAuditLogger>();
    private readonly ReactivateUsuarioCommandHandler _handler;

    public ReactivateUsuarioCommandHandlerTests()
    {
        _handler = new ReactivateUsuarioCommandHandler(_repo, _audit, TimeProvider.System);
    }

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

    [Fact]
    public async Task Handle_Reactivates_Inactive_User_Returns_Activo_True()
    {
        var target = MakeUser(5, false);
        var reactivated = MakeUser(5, true);

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

        var result = await _handler.Handle(new ReactivateUsuarioCommand(5));

        Assert.True(result.Activo);
        await _repo.Received(1).UpdateAsync(5, Arg.Any<UpdateUsuarioFields>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
    }

    [Fact]
    public async Task Handle_Idempotent_When_Already_Active()
    {
        var target = MakeUser(5, true); // already active
        _repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(target);

        var result = await _handler.Handle(new ReactivateUsuarioCommand(5));

        await _repo.DidNotReceive().UpdateAsync(Arg.Any<int>(), Arg.Any<UpdateUsuarioFields>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
        Assert.True(result.Activo);
    }

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

        await Assert.ThrowsAsync<UsuarioNotFoundException>(
            () => _handler.Handle(new ReactivateUsuarioCommand(9999)));
    }
}
