using Microsoft.Extensions.Diagnostics.HealthChecks;
using ZB.MOM.WW.Auth.ApiKeys.Sqlite;
using ZB.MOM.WW.MxGateway.Server.Diagnostics;

namespace ZB.MOM.WW.MxGateway.Tests.Diagnostics;

public sealed class AuthStoreHealthCheckTests
{
    private static AuthSqliteConnectionFactory FactoryFor(string sqlitePath)
    {
        // The shared connection factory targets a database path directly.
        return new AuthSqliteConnectionFactory(sqlitePath);
    }

    [Fact]
    public async Task Healthy_WhenStoreReachable()
    {
        var path = Path.Combine(Path.GetTempPath(), $"authcheck-{Guid.NewGuid():N}.db");
        try
        {
            var check = new AuthStoreHealthCheck(FactoryFor(path));
            var result = await check.CheckHealthAsync(new HealthCheckContext());
            Assert.Equal(HealthStatus.Healthy, result.Status);
        }
        finally { if (File.Exists(path)) File.Delete(path); }
    }

    [Fact]
    public async Task Unhealthy_WhenPathUnusable()
    {
        // A regular file used as a parent directory forces the open to fail.
        var bogus = Path.Combine(Path.GetTempPath(), $"authcheck-{Guid.NewGuid():N}");
        await File.WriteAllTextAsync(bogus, "x");
        try
        {
            var check = new AuthStoreHealthCheck(FactoryFor(Path.Combine(bogus, "store.db")));
            var result = await check.CheckHealthAsync(new HealthCheckContext());
            Assert.Equal(HealthStatus.Unhealthy, result.Status);
        }
        finally { if (File.Exists(bogus)) File.Delete(bogus); }
    }
}
