using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using ScadaLink.Commons.Messages.RemoteQuery;

namespace ScadaLink.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;

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

    public void Dispose()
    {
        if (File.Exists(_dbPath)) File.Delete(_dbPath);
    }

    private SiteEventLogger NewLogger() => new(
        Options.Create(new SiteEventLogOptions { DatabasePath = _dbPath }),
        NullLogger<SiteEventLogger>.Instance);

    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_CompletesWithoutThrowing()
    {
        // Logging after disposal must not throw or hang — the event is simply
        // dropped because the background writer has been completed.
        var logger = NewLogger();
        logger.Dispose();

        await logger.LogEventAsync("script", "Info", null, "Source", "After dispose")
            .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();
    }
}
