"""Provider database URLs are accepted as pasted (no database needed)."""
import pytest

from app.core.config import Settings
from app.core.dburl import connect_args_for, is_pooled, normalize_database_url


@pytest.mark.parametrize("given,expected", [
    ("postgres://u:p@h:5432/db", "postgresql+asyncpg://u:p@h:5432/db"),
    ("postgresql://u:p@h/db", "postgresql+asyncpg://u:p@h/db"),
    ("postgresql+asyncpg://u:p@localhost/x", "postgresql+asyncpg://u:p@localhost/x"),
    # Neon style: sslmode becomes asyncpg's ssl, channel_binding is dropped
    ("postgresql://u:p@ep-a.eu.aws.neon.tech/neondb?sslmode=require&channel_binding=require",
     "postgresql+asyncpg://u:p@ep-a.eu.aws.neon.tech/neondb?ssl=require"),
    ("postgres://u:p@h/db?sslmode=disable", "postgresql+asyncpg://u:p@h/db?ssl=disable"),
    ("  postgres://u:p@h/db  ", "postgresql+asyncpg://u:p@h/db"),
])
def test_urls_are_made_asyncpg_ready(given, expected):
    assert normalize_database_url(given) == expected


def test_a_password_with_special_characters_survives():
    url = "postgres://user:p%40ss%2Fw0rd@h/db?sslmode=require"
    assert normalize_database_url(url) == "postgresql+asyncpg://user:p%40ss%2Fw0rd@h/db?ssl=require"


def test_normalising_twice_changes_nothing():
    once = normalize_database_url("postgresql://u:p@h/db?sslmode=require")
    assert normalize_database_url(once) == once


def test_settings_apply_it_to_the_environment_value(monkeypatch):
    monkeypatch.setenv("DATABASE_URL", "postgres://u:p@h:5432/db?sslmode=require")
    assert Settings().database_url == "postgresql+asyncpg://u:p@h:5432/db?ssl=require"


@pytest.mark.parametrize("url,pooled", [
    ("postgresql://u:p@ep-quiet-sun-123-pooler.eu-central-1.aws.neon.tech/db", True),
    ("postgresql://u:p@db.example.supabase.co:6543/postgres", True),
    ("postgresql://u:p@ep-quiet-sun-123.eu-central-1.aws.neon.tech/db", False),
    ("postgresql+asyncpg://neuro:neuro@localhost:5432/neuro", False),
])
def test_pooled_connections_are_recognised(url, pooled):
    assert is_pooled(url) is pooled
    args = connect_args_for(url)
    assert bool(args) is pooled
    if pooled:  # no cached prepared statements, and unique names: safe behind a pooler
        assert args["statement_cache_size"] == 0 and args["prepared_statement_cache_size"] == 0
        assert args["prepared_statement_name_func"]() != args["prepared_statement_name_func"]()
