using FluentAssertions;
using Microsoft.Extensions.Time.Testing;
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using SIGCM2.Application.Abstractions.Persistence;
using SIGCM2.Application.Audit;
using SIGCM2.Application.ProductTypes.Deactivate;
using SIGCM2.Domain.Entities;
using SIGCM2.Domain.Exceptions;

namespace SIGCM2.Application.Tests.ProductTypes.Deactivate;

public class DeactivateProductTypeCommandHandlerTests
{
    private readonly IProductTypeRepository _repo = Substitute.For<IProductTypeRepository>();
    private readonly IProductQueryRepository _productQuery = Substitute.For<IProductQueryRepository>();
    private readonly IAuditLogger _audit = Substitute.For<IAuditLogger>();
    private readonly FakeTimeProvider _timeProvider = new(new DateTimeOffset(2026, 4, 19, 14, 0, 0, TimeSpan.Zero));
    private readonly DeactivateProductTypeCommandHandler _handler;

    public DeactivateProductTypeCommandHandlerTests()
    {
        _productQuery.ExistsActiveByProductTypeAsync(Arg.Any<int>(), Arg.Any<CancellationToken>()).Returns(false);
        _handler = new DeactivateProductTypeCommandHandler(_repo, _productQuery, _audit, _timeProvider);
    }

    private static ProductType ActiveType(int id = 1) =>
        new(id, "Clasificados", false, false, false, false, false, null, null, null, null,
            isActive: true, new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc), null);

    private static ProductType InactiveType(int id = 1) =>
        new(id, "Clasificados", false, false, false, false, false, null, null, null, null,
            isActive: false, new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc), null);

    // ── Not found ────────────────────────────────────────────────────────────

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

        var act = async () => await _handler.Handle(new DeactivateProductTypeCommand(99));

        await act.Should().ThrowAsync<ProductTypeNotFoundException>()
            .Where(e => e.ProductTypeId == 99);
    }

    // ── Already inactive (idempotent) ─────────────────────────────────────────

    [Fact]
    public async Task Handle_AlreadyInactive_ReturnsIdempotentDto_NoAudit_NoRepoUpdate()
    {
        _repo.GetByIdAsync(1, Arg.Any<CancellationToken>()).Returns(InactiveType());

        var result = await _handler.Handle(new DeactivateProductTypeCommand(1));

        result.Id.Should().Be(1);
        result.IsActive.Should().BeFalse();
        await _repo.DidNotReceive().UpdateAsync(Arg.Any<ProductType>(), Arg.Any<CancellationToken>());
        await _audit.DidNotReceive().LogAsync(
            Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
            Arg.Any<object?>(), Arg.Any<CancellationToken>());
    }

    // ── In use guard ─────────────────────────────────────────────────────────

    [Fact]
    public async Task Handle_InUseGuardReturnsTrue_ThrowsProductTypeEnUsoException()
    {
        _repo.GetByIdAsync(1, Arg.Any<CancellationToken>()).Returns(ActiveType());
        _productQuery.ExistsActiveByProductTypeAsync(1, Arg.Any<CancellationToken>()).Returns(true);

        var act = async () => await _handler.Handle(new DeactivateProductTypeCommand(1));

        await act.Should().ThrowAsync<ProductTypeEnUsoException>()
            .Where(e => e.ProductTypeId == 1);
    }

    [Fact]
    public async Task Handle_CallsIProductQueryRepository_Received1()
    {
        _repo.GetByIdAsync(1, Arg.Any<CancellationToken>()).Returns(ActiveType());

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

        await _productQuery.Received(1).ExistsActiveByProductTypeAsync(1, Arg.Any<CancellationToken>());
    }

    // ── Happy path ───────────────────────────────────────────────────────────

    [Fact]
    public async Task Handle_ValidDeactivation_UpdatesAndAuditsProductoTipoDeactivated()
    {
        _repo.GetByIdAsync(1, Arg.Any<CancellationToken>()).Returns(ActiveType());

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

        await _repo.Received(1).UpdateAsync(
            Arg.Is<ProductType>(pt => !pt.IsActive),
            Arg.Any<CancellationToken>());
        await _audit.Received(1).LogAsync(
            action: "producto_tipo.deactivated",
            targetType: "ProductType",
            targetId: "1",
            metadata: Arg.Any<object?>(),
            ct: Arg.Any<CancellationToken>());
    }

    [Fact]
    public async Task Handle_UsesTimeProviderInDeactivate()
    {
        _repo.GetByIdAsync(1, Arg.Any<CancellationToken>()).Returns(ActiveType());
        var expectedDate = _timeProvider.GetUtcNow().UtcDateTime;

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

        await _repo.Received(1).UpdateAsync(
            Arg.Is<ProductType>(pt => pt.FechaModificacion == expectedDate),
            Arg.Any<CancellationToken>());
    }

    [Fact]
    public async Task Handle_ReturnsDtoWithIdAndIsActiveFalse()
    {
        _repo.GetByIdAsync(1, Arg.Any<CancellationToken>()).Returns(ActiveType());

        var result = await _handler.Handle(new DeactivateProductTypeCommand(1));

        result.Id.Should().Be(1);
        result.IsActive.Should().BeFalse();
    }

    // ── Rollback scenarios ────────────────────────────────────────────────────

    [Fact]
    public async Task Handle_RepoThrows_Rollback()
    {
        _repo.GetByIdAsync(1, Arg.Any<CancellationToken>()).Returns(ActiveType());
        _repo.UpdateAsync(Arg.Any<ProductType>(), Arg.Any<CancellationToken>())
             .ThrowsAsync(new InvalidOperationException("DB"));

        var act = async () => await _handler.Handle(new DeactivateProductTypeCommand(1));

        await act.Should().ThrowAsync<InvalidOperationException>();
    }

    [Fact]
    public async Task Handle_AuditThrows_Rollback()
    {
        _repo.GetByIdAsync(1, Arg.Any<CancellationToken>()).Returns(ActiveType());
        _audit.LogAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
            Arg.Any<object?>(), Arg.Any<CancellationToken>())
            .ThrowsAsync(new InvalidOperationException("Audit"));

        var act = async () => await _handler.Handle(new DeactivateProductTypeCommand(1));

        await act.Should().ThrowAsync<InvalidOperationException>();
    }
}
