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

namespace SIGCM2.Application.Tests.TiposDeIva.Reactivate;

public class ReactivateTipoDeIvaCommandHandlerTests
{
    private readonly ITipoDeIvaRepository _repo = Substitute.For<ITipoDeIvaRepository>();
    private readonly IAuditLogger _audit = Substitute.For<IAuditLogger>();
    private readonly ReactivateTipoDeIvaCommandHandler _handler;

    private static TipoDeIva MakeEntity(bool activo = false) => TipoDeIva.FromDb(
        id: 1, codigo: "IVA_21", descripcion: "IVA 21%", porcentaje: 21m, aplicaIVA: true,
        activo: activo, vigenciaDesde: new DateOnly(2024, 1, 1), vigenciaHasta: null,
        predecesorId: null, fechaCreacion: DateTime.UtcNow, fechaModificacion: null);

    public ReactivateTipoDeIvaCommandHandlerTests()
    {
        _handler = new ReactivateTipoDeIvaCommandHandler(_repo, _audit, TimeProvider.System);
        _repo.GetByIdAsync(1, Arg.Any<CancellationToken>()).Returns(MakeEntity());
        _repo.SetActivoAsync(Arg.Any<int>(), Arg.Any<bool>(), Arg.Any<CancellationToken>()).Returns(true);
    }

    [Fact]
    public async Task Handle_NotFound_ThrowsTipoDeIvaNotFoundException()
    {
        _repo.GetByIdAsync(99, Arg.Any<CancellationToken>()).Returns((TipoDeIva?)null);

        await Assert.ThrowsAsync<TipoDeIvaNotFoundException>(
            () => _handler.Handle(new ReactivateTipoDeIvaCommand(99)));
    }

    [Fact]
    public async Task Handle_HappyPath_CallsSetActivoTrue()
    {
        await _handler.Handle(new ReactivateTipoDeIvaCommand(1));

        await _repo.Received(1).SetActivoAsync(1, true, Arg.Any<CancellationToken>());
    }

    [Fact]
    public async Task Handle_HappyPath_CallsAuditReactivate()
    {
        await _handler.Handle(new ReactivateTipoDeIvaCommand(1));

        await _audit.Received(1).LogAsync(
            action: "tipo_iva.reactivate",
            targetType: "TipoDeIva",
            targetId: "1",
            metadata: Arg.Any<object?>(),
            ct: Arg.Any<CancellationToken>());
    }

    [Fact]
    public async Task Handle_AlreadyActive_IsIdempotent_NoAudit()
    {
        _repo.GetByIdAsync(1, Arg.Any<CancellationToken>()).Returns(MakeEntity(activo: true));

        await _handler.Handle(new ReactivateTipoDeIvaCommand(1));

        await _audit.DidNotReceive().LogAsync(
            Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
            Arg.Any<object?>(), Arg.Any<CancellationToken>());
    }
}
