using System.Text.Json;

namespace KArtSell.Integration.Tests;

internal static class TestDatabaseConnection
{
    public static string GetConnectionString()
    {
        var configured = Environment.GetEnvironmentVariable("KARTSELL_POSTGRES");
        if (!string.IsNullOrWhiteSpace(configured))
            return configured;

        var path = Path.Combine(AppContext.BaseDirectory, "appsettings.Development.json");
        if (!File.Exists(path))
            throw new InvalidOperationException($"Integration test settings are required: {path}");

        using var document = JsonDocument.Parse(File.ReadAllText(path));
        if (!document.RootElement.TryGetProperty("ConnectionStrings", out var connectionStrings) ||
            !connectionStrings.TryGetProperty("Postgres", out var postgres) ||
            string.IsNullOrWhiteSpace(postgres.GetString()))
        {
            throw new InvalidOperationException(
                "ConnectionStrings:Postgres is required in appsettings.Development.json.");
        }

        return postgres.GetString()!;
    }
}
