"""
Alembic round-trip test.

Verifies that ``alembic upgrade head`` followed by ``alembic downgrade base``
runs without error against a Postgres throwaway database. Skipped when no
Postgres is reachable (the migrations rely on PG-specific types and cannot
target SQLite).
"""

from __future__ import annotations

import os
import pathlib
import subprocess
import pytest

BACKEND_ROOT = pathlib.Path(__file__).resolve().parent.parent


@pytest.mark.requires_postgres
def test_alembic_upgrade_head_roundtrip():
    dsn = os.environ.get("TEST_DATABASE_URL") or os.environ.get("DATABASE_URL")
    assert dsn, "TEST_DATABASE_URL or DATABASE_URL must be set"

    env = os.environ.copy()
    env["DATABASE_URL"] = dsn

    # The session fixture has already upgraded; downgrade then re-upgrade to
    # exercise both paths inside this test without polluting the rest of the
    # session schema state.
    down = subprocess.run(
        ["alembic", "downgrade", "base"],
        cwd=str(BACKEND_ROOT),
        env=env,
        capture_output=True,
        text=True,
    )
    assert down.returncode == 0, f"downgrade failed: {down.stderr}"

    up = subprocess.run(
        ["alembic", "upgrade", "head"],
        cwd=str(BACKEND_ROOT),
        env=env,
        capture_output=True,
        text=True,
    )
    assert up.returncode == 0, f"upgrade failed: {up.stderr}"
