using NSubstitute;
using SIGCM2.Application.Abstractions.Persistence;
using SIGCM2.Application.Audit;
using SIGCM2.Application.PuntosDeVenta.Update;
using SIGCM2.Domain.Entities;
using SIGCM2.Domain.Exceptions;

namespace SIGCM2.Application.Tests.PuntosDeVenta.Update;

public class UpdatePuntoDeVentaCommandHandlerTests
{
    private readonly IPuntoDeVentaRepository _repo = Substitute.For<IPuntoDeVentaRepository>();
    private readonly IMedioRepository _medioRepo = Substitute.For<IMedioRepository>();
    private readonly IAuditLogger _audit = Substitute.For<IAuditLogger>();
    private readonly UpdatePuntoDeVentaCommandHandler _handler;

    private static PuntoDeVenta MakePdv(int id = 10, int medioId = 5, bool activo = true)
        => new(id, medioId, 1, "Original", null, activo, DateTime.UtcNow, null);

    private static Medio MakeMedio(int id = 5, bool activo = true)
        => new(id, "COD" + id, "Medio " + id, TipoMedio.Diario, null, activo, DateTime.UtcNow, null);

    private static UpdatePuntoDeVentaCommand ValidCommand(int id = 10) =>
        new(Id: id, Nombre: "Nuevo Nombre", NumeroAFIP: 3, Descripcion: null);

    public UpdatePuntoDeVentaCommandHandlerTests()
    {
        _handler = new UpdatePuntoDeVentaCommandHandler(_repo, _medioRepo, _audit, TimeProvider.System);
        _repo.GetByIdAsync(10, Arg.Any<CancellationToken>()).Returns(MakePdv(10));
        _medioRepo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(MakeMedio(5));
        _repo.ExistsByNumeroAFIPInMedioAsync(Arg.Any<int>(), Arg.Any<short>(), Arg.Any<int?>(), Arg.Any<CancellationToken>()).Returns(false);
    }

    [Fact]
    public async Task Handle_NotFound_ThrowsPuntoDeVentaNotFoundException()
    {
        _repo.GetByIdAsync(999, Arg.Any<CancellationToken>()).Returns((PuntoDeVenta?)null);

        await Assert.ThrowsAsync<PuntoDeVentaNotFoundException>(
            () => _handler.Handle(new UpdatePuntoDeVentaCommand(999, "X", 1, null)));
    }

    [Fact]
    public async Task Handle_MedioInactivo_ThrowsMedioInactivoException()
    {
        _medioRepo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(MakeMedio(5, false));

        await Assert.ThrowsAsync<MedioInactivoException>(
            () => _handler.Handle(ValidCommand()));
    }

    [Fact]
    public async Task Handle_NumeroAFIPDuplicado_ThrowsNumeroAFIPDuplicadoException()
    {
        _repo.ExistsByNumeroAFIPInMedioAsync(5, 3, 10, Arg.Any<CancellationToken>()).Returns(true);

        await Assert.ThrowsAsync<NumeroAFIPDuplicadoException>(
            () => _handler.Handle(ValidCommand()));
    }

    [Fact]
    public async Task Handle_HappyPath_CallsUpdateAsyncOnce()
    {
        await _handler.Handle(ValidCommand());

        await _repo.Received(1).UpdateAsync(Arg.Any<PuntoDeVenta>(), Arg.Any<CancellationToken>());
    }

    [Fact]
    public async Task Handle_HappyPath_ReturnsDtoWithUpdatedFields()
    {
        var result = await _handler.Handle(ValidCommand());

        Assert.Equal(10, result.Id);
        Assert.Equal("Nuevo Nombre", result.Nombre);
        Assert.Equal(3, result.NumeroAFIP);
    }

    [Fact]
    public async Task Handle_HappyPath_CallsAuditWithUpdateAction()
    {
        await _handler.Handle(ValidCommand());

        await _audit.Received(1).LogAsync(
            action: "punto_de_venta.update",
            targetType: "PuntoDeVenta",
            targetId: "10",
            metadata: Arg.Any<object?>(),
            ct: Arg.Any<CancellationToken>());
    }

    [Fact]
    public async Task Handle_MedioInactivo_NoAuditLogged()
    {
        _medioRepo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(MakeMedio(5, false));

        try { await _handler.Handle(ValidCommand()); } catch (MedioInactivoException) { }

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