using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using ScadaLink.Commons.Entities.ExternalSystems;
using ScadaLink.Commons.Interfaces.Repositories;

namespace ScadaLink.ExternalSystemGateway.Tests;

/// <summary>
/// WP-9: Tests for Database access — connection resolution, cached writes.
/// </summary>
public class DatabaseGatewayTests
{
    private readonly IExternalSystemRepository _repository = Substitute.For<IExternalSystemRepository>();

    [Fact]
    public async Task GetConnection_NotFound_Throws()
    {
        _repository.GetAllDatabaseConnectionsAsync().Returns(new List<DatabaseConnectionDefinition>());

        var gateway = new DatabaseGateway(
            _repository,
            NullLogger<DatabaseGateway>.Instance);

        await Assert.ThrowsAsync<InvalidOperationException>(
            () => gateway.GetConnectionAsync("nonexistent"));
    }

    [Fact]
    public async Task CachedWrite_NoStoreAndForward_Throws()
    {
        var conn = new DatabaseConnectionDefinition("testDb", "Server=localhost;Database=test") { Id = 1 };
        _repository.GetAllDatabaseConnectionsAsync()
            .Returns(new List<DatabaseConnectionDefinition> { conn });

        var gateway = new DatabaseGateway(
            _repository,
            NullLogger<DatabaseGateway>.Instance,
            storeAndForward: null);

        await Assert.ThrowsAsync<InvalidOperationException>(
            () => gateway.CachedWriteAsync("testDb", "INSERT INTO t VALUES (1)"));
    }

    [Fact]
    public async Task CachedWrite_ConnectionNotFound_Throws()
    {
        _repository.GetAllDatabaseConnectionsAsync().Returns(new List<DatabaseConnectionDefinition>());

        var gateway = new DatabaseGateway(
            _repository,
            NullLogger<DatabaseGateway>.Instance);

        await Assert.ThrowsAsync<InvalidOperationException>(
            () => gateway.CachedWriteAsync("nonexistent", "INSERT INTO t VALUES (1)"));
    }
}
