using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using NSubstitute;
using ScadaLink.Commons.Entities.Deployment;
using ScadaLink.Commons.Entities.Instances;
using ScadaLink.Commons.Interfaces.Repositories;
using ScadaLink.Commons.Interfaces.Services;
using ScadaLink.Commons.Messages.Deployment;
using ScadaLink.Commons.Messages.Lifecycle;
using ScadaLink.Commons.Types;
using ScadaLink.Commons.Types.Enums;
using ScadaLink.Commons.Types.Flattening;
using ScadaLink.Communication;

namespace ScadaLink.DeploymentManager.Tests;

/// <summary>
/// WP-1/2/4/5/6/8/16: Tests for central-side DeploymentService.
/// </summary>
public class DeploymentServiceTests
{
    private readonly IDeploymentManagerRepository _repo;
    private readonly IFlatteningPipeline _pipeline;
    private readonly CommunicationService _comms;
    private readonly OperationLockManager _lockManager;
    private readonly IAuditService _audit;
    private readonly DeploymentService _service;

    public DeploymentServiceTests()
    {
        _repo = Substitute.For<IDeploymentManagerRepository>();
        _pipeline = Substitute.For<IFlatteningPipeline>();
        _comms = new CommunicationService(
            Options.Create(new CommunicationOptions()),
            NullLogger<CommunicationService>.Instance);
        _lockManager = new OperationLockManager();
        _audit = Substitute.For<IAuditService>();

        var options = Options.Create(new DeploymentManagerOptions
        {
            OperationLockTimeout = TimeSpan.FromSeconds(5)
        });

        var siteRepo = Substitute.For<ISiteRepository>();
        _service = new DeploymentService(
            _repo, siteRepo, _pipeline, _comms, _lockManager, _audit, options,
            NullLogger<DeploymentService>.Instance);
    }

    // ── WP-1: Deployment flow ──

    [Fact]
    public async Task DeployInstanceAsync_InstanceNotFound_ReturnsFailure()
    {
        _repo.GetInstanceByIdAsync(1).Returns((Instance?)null);

        var result = await _service.DeployInstanceAsync(1, "admin");

        Assert.True(result.IsFailure);
        Assert.Contains("not found", result.Error);
    }

    [Fact]
    public async Task DeployInstanceAsync_ValidationFails_ReturnsFailure()
    {
        var instance = new Instance("TestInst") { Id = 1, SiteId = 1, State = InstanceState.NotDeployed };
        _repo.GetInstanceByIdAsync(1).Returns(instance);

        var validationResult = new ValidationResult
        {
            Errors = [ValidationEntry.Error(ValidationCategory.ScriptCompilation, "Compile error")]
        };
        _pipeline.FlattenAndValidateAsync(1, Arg.Any<CancellationToken>())
            .Returns(Result<FlatteningPipelineResult>.Success(
                new FlatteningPipelineResult(new FlattenedConfiguration(), "hash1", validationResult)));

        var result = await _service.DeployInstanceAsync(1, "admin");

        Assert.True(result.IsFailure);
        Assert.Contains("validation failed", result.Error);
    }

    [Fact]
    public async Task DeployInstanceAsync_FlatteningFails_ReturnsFailure()
    {
        var instance = new Instance("TestInst") { Id = 1, SiteId = 1, State = InstanceState.NotDeployed };
        _repo.GetInstanceByIdAsync(1).Returns(instance);

        _pipeline.FlattenAndValidateAsync(1, Arg.Any<CancellationToken>())
            .Returns(Result<FlatteningPipelineResult>.Failure("Template chain empty"));

        var result = await _service.DeployInstanceAsync(1, "admin");

        Assert.True(result.IsFailure);
        Assert.Contains("Validation failed", result.Error);
    }

    // ── WP-2: Deployment identity ──

    [Fact]
    public async Task DeployInstanceAsync_CreatesUniqueDeploymentId()
    {
        var instance = new Instance("TestInst") { Id = 1, SiteId = 1, State = InstanceState.NotDeployed };
        _repo.GetInstanceByIdAsync(1).Returns(instance);

        // Pipeline succeeds
        var config = new FlattenedConfiguration { InstanceUniqueName = "TestInst" };
        var validResult = ValidationResult.Success();
        _pipeline.FlattenAndValidateAsync(1, Arg.Any<CancellationToken>())
            .Returns(Result<FlatteningPipelineResult>.Success(
                new FlatteningPipelineResult(config, "sha256:abc", validResult)));

        // Capture the deployment record
        DeploymentRecord? captured = null;
        await _repo.AddDeploymentRecordAsync(Arg.Do<DeploymentRecord>(r => captured = r), Arg.Any<CancellationToken>());

        // CommunicationService will throw because actor not set -- this tests the flow up to that point
        try
        {
            await _service.DeployInstanceAsync(1, "admin");
        }
        catch (InvalidOperationException)
        {
            // Expected -- CommunicationService not initialized
        }

        Assert.NotNull(captured);
        Assert.False(string.IsNullOrEmpty(captured!.DeploymentId));
        Assert.Equal(32, captured.DeploymentId.Length); // GUID without hyphens
        Assert.Equal("sha256:abc", captured.RevisionHash);
    }

    // ── WP-4: State transition validation ──

    [Fact]
    public async Task DeployInstanceAsync_EnabledInstance_AllowsDeploy()
    {
        var instance = new Instance("TestInst") { Id = 1, SiteId = 1, State = InstanceState.Enabled };
        _repo.GetInstanceByIdAsync(1).Returns(instance);

        var config = new FlattenedConfiguration { InstanceUniqueName = "TestInst" };
        _pipeline.FlattenAndValidateAsync(1, Arg.Any<CancellationToken>())
            .Returns(Result<FlatteningPipelineResult>.Success(
                new FlatteningPipelineResult(config, "hash", ValidationResult.Success())));

        // Will fail at communication layer, but passes state validation
        try { await _service.DeployInstanceAsync(1, "admin"); } catch (InvalidOperationException) { }

        // If we got past state validation, the deployment record was created
        await _repo.Received().AddDeploymentRecordAsync(Arg.Any<DeploymentRecord>(), Arg.Any<CancellationToken>());
    }

    // ── WP-6: Lifecycle commands ──

    [Fact]
    public async Task DisableInstanceAsync_InstanceNotFound_ReturnsFailure()
    {
        _repo.GetInstanceByIdAsync(1).Returns((Instance?)null);

        var result = await _service.DisableInstanceAsync(1, "admin");

        Assert.True(result.IsFailure);
        Assert.Contains("not found", result.Error);
    }

    [Fact]
    public async Task DisableInstanceAsync_WhenDisabled_ReturnsTransitionError()
    {
        var instance = new Instance("TestInst") { Id = 1, SiteId = 1, State = InstanceState.Disabled };
        _repo.GetInstanceByIdAsync(1).Returns(instance);

        var result = await _service.DisableInstanceAsync(1, "admin");

        Assert.True(result.IsFailure);
        Assert.Contains("not allowed", result.Error);
    }

    [Fact]
    public async Task EnableInstanceAsync_WhenEnabled_ReturnsTransitionError()
    {
        var instance = new Instance("TestInst") { Id = 1, SiteId = 1, State = InstanceState.Enabled };
        _repo.GetInstanceByIdAsync(1).Returns(instance);

        var result = await _service.EnableInstanceAsync(1, "admin");

        Assert.True(result.IsFailure);
        Assert.Contains("not allowed", result.Error);
    }

    [Fact]
    public async Task DeleteInstanceAsync_WhenNotDeployed_ReturnsTransitionError()
    {
        var instance = new Instance("TestInst") { Id = 1, SiteId = 1, State = InstanceState.NotDeployed };
        _repo.GetInstanceByIdAsync(1).Returns(instance);

        var result = await _service.DeleteInstanceAsync(1, "admin");

        Assert.True(result.IsFailure);
        Assert.Contains("not allowed", result.Error);
    }

    // ── WP-8: Deployment comparison ──

    [Fact]
    public async Task GetDeploymentComparisonAsync_NoSnapshot_ReturnsFailure()
    {
        _repo.GetDeployedSnapshotByInstanceIdAsync(1).Returns((DeployedConfigSnapshot?)null);

        var result = await _service.GetDeploymentComparisonAsync(1);

        Assert.True(result.IsFailure);
        Assert.Contains("No deployed snapshot", result.Error);
    }

    [Fact]
    public async Task GetDeploymentComparisonAsync_SameHash_NotStale()
    {
        var snapshot = new DeployedConfigSnapshot("dep1", "sha256:abc", "{}")
        {
            InstanceId = 1,
            DeployedAt = DateTimeOffset.UtcNow
        };
        _repo.GetDeployedSnapshotByInstanceIdAsync(1).Returns(snapshot);

        var config = new FlattenedConfiguration { InstanceUniqueName = "TestInst" };
        _pipeline.FlattenAndValidateAsync(1, Arg.Any<CancellationToken>())
            .Returns(Result<FlatteningPipelineResult>.Success(
                new FlatteningPipelineResult(config, "sha256:abc", ValidationResult.Success())));

        var result = await _service.GetDeploymentComparisonAsync(1);

        Assert.True(result.IsSuccess);
        Assert.False(result.Value.IsStale);
    }

    [Fact]
    public async Task GetDeploymentComparisonAsync_DifferentHash_IsStale()
    {
        var snapshot = new DeployedConfigSnapshot("dep1", "sha256:abc", "{}")
        {
            InstanceId = 1,
            DeployedAt = DateTimeOffset.UtcNow
        };
        _repo.GetDeployedSnapshotByInstanceIdAsync(1).Returns(snapshot);

        var config = new FlattenedConfiguration { InstanceUniqueName = "TestInst" };
        _pipeline.FlattenAndValidateAsync(1, Arg.Any<CancellationToken>())
            .Returns(Result<FlatteningPipelineResult>.Success(
                new FlatteningPipelineResult(config, "sha256:xyz", ValidationResult.Success())));

        var result = await _service.GetDeploymentComparisonAsync(1);

        Assert.True(result.IsSuccess);
        Assert.True(result.Value.IsStale);
    }

    // ── WP-2: GetDeploymentStatusAsync ──

    [Fact]
    public async Task GetDeploymentStatusAsync_ReturnsRecordByDeploymentId()
    {
        var record = new DeploymentRecord("dep1", "admin")
        {
            Status = DeploymentStatus.Success
        };
        _repo.GetDeploymentByDeploymentIdAsync("dep1").Returns(record);

        var result = await _service.GetDeploymentStatusAsync("dep1");

        Assert.NotNull(result);
        Assert.Equal("dep1", result!.DeploymentId);
        Assert.Equal(DeploymentStatus.Success, result.Status);
    }

    // ── Audit logging ──

    [Fact]
    public async Task DeployInstanceAsync_AuditLogs()
    {
        var instance = new Instance("TestInst") { Id = 1, SiteId = 1, State = InstanceState.NotDeployed };
        _repo.GetInstanceByIdAsync(1).Returns(instance);

        _pipeline.FlattenAndValidateAsync(1, Arg.Any<CancellationToken>())
            .Returns(Result<FlatteningPipelineResult>.Failure("Error"));

        await _service.DeployInstanceAsync(1, "admin");

        // Failure case does not reach audit (returns before communication)
        // The audit is only logged after communication succeeds/fails
    }
}
