using Npgsql;

namespace Tiku.IntegrationTests.Infrastructure;

internal static class DockerPostgresTestDefaults
{
    internal static string AdminConnectionString => CreateConnectionString("postgres", false);

    internal static string CreateConnectionString(string database, bool pooling = true)
    {
        return new NpgsqlConnectionStringBuilder
        {
            Host = "127.0.0.1",
            Port = ParsePort(Environment.GetEnvironmentVariable("TIKU_POSTGRES_PORT")),
            Database = database,
            Username = Environment.GetEnvironmentVariable("TIKU_POSTGRES_USER") ?? "tiku",
            Password = Environment.GetEnvironmentVariable("TIKU_POSTGRES_PASSWORD") ?? "tiku_dev",
            Pooling = pooling,
            Timeout = 5,
            CommandTimeout = 60
        }.ConnectionString;
    }

    private static int ParsePort(string? value)
    {
        return int.TryParse(value, out var port) && port is >= 1 and <= 65535 ? port : 5432;
    }
}
