using NSubstitute;
using SIGCM2.Application.Abstractions.Persistence;
using SIGCM2.Application.Audit;
using SIGCM2.Application.IngresosBrutos.Reactivate;
using SIGCM2.Domain.Exceptions;
using SIGCM2.Domain.Fiscal;
using IibbEntity = SIGCM2.Domain.Entities.IngresosBrutos;

namespace SIGCM2.Application.Tests.IngresosBrutos.Reactivate;

public class ReactivateIngresosBrutosCommandHandlerTests
{
    private readonly IIngresosBrutosRepository _repo = Substitute.For<IIngresosBrutosRepository>();
    private readonly IAuditLogger _audit = Substitute.For<IAuditLogger>();
    private readonly ReactivateIngresosBrutosCommandHandler _handler;

    private static IibbEntity MakeEntity(bool activo = false) =>
        IibbEntity.FromDb(
            id: 1, provincia: ProvinciaArgentina.BuenosAires, descripcion: "IIBB BA",
            alicuota: 3m, activo: activo,
            vigenciaDesde: new DateOnly(2024, 1, 1),
            vigenciaHasta: null, predecesorId: null,
            fechaCreacion: DateTime.UtcNow, fechaModificacion: null);

    public ReactivateIngresosBrutosCommandHandlerTests()
    {
        _handler = new ReactivateIngresosBrutosCommandHandler(_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_ThrowsIngresosBrutosNotFoundException()
    {
        _repo.GetByIdAsync(99, Arg.Any<CancellationToken>()).Returns((IibbEntity?)null);

        await Assert.ThrowsAsync<IngresosBrutosNotFoundException>(
            () => _handler.Handle(new ReactivateIngresosBrutosCommand(99)));
    }

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

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

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

        await _audit.Received(1).LogAsync(
            action: "ingresos_brutos.reactivate",
            targetType: "IngresosBrutos",
            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 ReactivateIngresosBrutosCommand(1));

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