using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.RemoteQuery;

namespace ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests;

/// <summary>
/// Regression tests for SiteEventLogging-010: previously untested behaviours —
/// the query service error path and the recorder's disposed-state semantics.
/// </summary>
public class EventLogCoverageTests : IDisposable
{
    private readonly string _dbPath;
    private readonly TestLocalDb _localDb;

    public EventLogCoverageTests()
    {
        _dbPath = Path.Combine(Path.GetTempPath(), $"test_coverage_{Guid.NewGuid()}.db");
        _localDb = TestLocalDb.Create(_dbPath);
    }

    public void Dispose()
    {
        _localDb.Dispose();
        TestLocalDb.DeleteFiles(_dbPath);
        GC.SuppressFinalize(this);
    }

    // Each call gets its own connection from the one shared local database, so the
    // loggers these tests dispose mid-test do not tear down the database itself.
    private SiteEventLogger NewLogger() => new(
        Options.Create(new SiteEventLogOptions { DatabasePath = _dbPath }),
        NullLogger<SiteEventLogger>.Instance,
        _localDb.Db);

    private static EventLogQueryRequest MakeRequest() => new(
        CorrelationId: "corr-err",
        SiteId: "site-1",
        From: null,
        To: null,
        EventType: null,
        Severity: null,
        InstanceId: null,
        KeywordFilter: null,
        ContinuationToken: null,
        PageSize: 500,
        Timestamp: DateTimeOffset.UtcNow);

    [Fact]
    public void ExecuteQuery_ReturnsFailureResponse_WhenDatabaseUnavailable()
    {
        // The catch block in EventLogQueryService.ExecuteQuery was untested.
        // Disposing the recorder makes WithConnection throw ObjectDisposedException;
        // the query service must convert that into a Success=false response rather
        // than letting the exception escape to the actor.
        var logger = NewLogger();
        var queryService = new EventLogQueryService(
            logger,
            Options.Create(new SiteEventLogOptions { DatabasePath = _dbPath }),
            NullLogger<EventLogQueryService>.Instance);

        logger.Dispose();

        var response = queryService.ExecuteQuery(MakeRequest());

        Assert.False(response.Success);
        Assert.NotNull(response.ErrorMessage);
        Assert.Empty(response.Entries);
        Assert.Null(response.ContinuationToken);
        Assert.Equal("corr-err", response.CorrelationId);
    }

    [Fact]
    public async Task LogEventAsync_AfterDispose_FaultsTask_NotReportsSuccess()
    {
        // SiteEventLogging-012: when the logger has been disposed the event cannot
        // be persisted. The returned Task must FAULT (not complete successfully) so
        // an awaiting caller can distinguish a dropped audit event from a written
        // one. Per the XML doc contract, the Task "faults if the write fails".
        var logger = NewLogger();
        logger.Dispose();

        var task = logger.LogEventAsync("script", "Info", null, "Source", "After dispose");

        await Assert.ThrowsAsync<ObjectDisposedException>(
            () => task.WaitAsync(TimeSpan.FromSeconds(5)));
    }

    [Fact]
    public void Dispose_IsIdempotent()
    {
        // Re-entrant / repeated Dispose must be a safe no-op.
        var logger = NewLogger();
        logger.Dispose();
        logger.Dispose();
    }

    [Fact]
    public async Task LogEventAsync_EnqueuedThenDisposed_FaultsTask_WhenWriteCannotComplete()
    {
        // SiteEventLogging-012, second path: an event enqueued onto the background
        // writer just before disposal must NOT be reported as persisted if the
        // writer's WithConnection returns false (logger disposed mid-drain). We
        // flood the queue and dispose immediately; any event whose write did not
        // actually run must have a faulted Task, never a successful one.
        var logger = NewLogger();

        var tasks = new List<Task>();
        for (int i = 0; i < 200; i++)
        {
            tasks.Add(logger.LogEventAsync("script", "Info", null, "Source", $"event-{i}"));
        }

        logger.Dispose();

        // Every task must reach a terminal state. None may be left as a successful
        // completion for an event the writer never persisted: a task is either
        // RanToCompletion (genuinely written before the connection closed) or
        // Faulted (could not be persisted). Count persisted vs faulted and assert
        // the persisted count matches the actual row count.
        await Task.WhenAll(tasks.Select(t => t.ContinueWith(_ => { })));

        var succeeded = tasks.Count(t => t.Status == TaskStatus.RanToCompletion);
        var faulted = tasks.Count(t => t.IsFaulted);
        Assert.Equal(tasks.Count, succeeded + faulted);

        long rowCount;
        using (var conn = new Microsoft.Data.Sqlite.SqliteConnection($"Data Source={_dbPath}"))
        {
            conn.Open();
            using var cmd = conn.CreateCommand();
            cmd.CommandText = "SELECT COUNT(*) FROM site_events";
            rowCount = (long)cmd.ExecuteScalar()!;
        }

        // A successfully-completed Task must correspond to a row that was actually
        // written. If the disposed-mid-drain path falsely reported success, the
        // success count would exceed the row count.
        Assert.Equal(rowCount, succeeded);
    }
}
