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

namespace SIGCM2.Application.Tests.Medios.Update;

public class UpdateMedioCommandHandlerTests
{
    private readonly IMedioRepository _repo = Substitute.For<IMedioRepository>();
    private readonly IAuditLogger _audit = Substitute.For<IAuditLogger>();
    private readonly UpdateMedioCommandHandler _handler;

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

    private static UpdateMedioCommand ValidCommand(int id = 1) => new(
        Id: id,
        Nombre: "Nuevo Nombre",
        Tipo: TipoMedio.Radio,
        PlataformaEmpresaId: 5);

    public UpdateMedioCommandHandlerTests()
    {
        _handler = new UpdateMedioCommandHandler(_repo, _audit, TimeProvider.System);
    }

    // ── not found → throws ──────────────────────────────────────────────────

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

        await Assert.ThrowsAsync<MedioNotFoundException>(
            () => _handler.Handle(new UpdateMedioCommand(999, "X", TipoMedio.Diario, null)));
    }

    // ── happy path ───────────────────────────────────────────────────────────

    [Fact]
    public async Task Handle_HappyPath_CallsUpdateAsyncOnce()
    {
        var medio = MakeMedio(1);
        _repo.GetByIdAsync(1, Arg.Any<CancellationToken>()).Returns(medio);

        await _handler.Handle(ValidCommand(1));

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

    [Fact]
    public async Task Handle_HappyPath_ReturnsDtoWithUpdatedFields()
    {
        var medio = MakeMedio(1, "Original", TipoMedio.Diario);
        _repo.GetByIdAsync(1, Arg.Any<CancellationToken>()).Returns(medio);

        var result = await _handler.Handle(ValidCommand(1));

        Assert.Equal(1, result.Id);
        Assert.Equal("Nuevo Nombre", result.Nombre);
        Assert.Equal(TipoMedio.Radio, result.Tipo);
        Assert.Equal(5, result.PlataformaEmpresaId);
    }

    [Fact]
    public async Task Handle_HappyPath_CallsAuditWithUpdateAction()
    {
        var medio = MakeMedio(1);
        _repo.GetByIdAsync(1, Arg.Any<CancellationToken>()).Returns(medio);

        await _handler.Handle(ValidCommand(1));

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