"""Persist project runtime invariants (admin path, persistence requirement, etc).

Core has always re-derived infrastructure/route decisions from prose at codegen
time and never persisted them, so a later, unrelated run could silently reset a
user-named admin path back to the "/admin" default, or forget that a form's
submissions must be readable in an admin view. This adds durable storage for
those facts (JSONB on projects) plus the columns Cloud's auth config will need
in a later phase to stop defaulting magic-link/reset "next" to "/admin".

Nothing reads or writes these columns yet outside this migration; the extractor
and its wiring land in the same change set as this migration.

Revision ID: 127
Revises: 126
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy import inspect
from sqlalchemy.dialects import postgresql

revision = "127"
down_revision = "126"
branch_labels = None
depends_on = None


def upgrade() -> None:
    conn = op.get_bind()
    insp = inspect(conn)

    project_cols = {c["name"] for c in insp.get_columns("projects")}
    if "runtime_invariants" not in project_cols:
        op.add_column(
            "projects",
            sa.Column(
                "runtime_invariants",
                postgresql.JSONB(),
                nullable=False,
                server_default=sa.text("'{}'::jsonb"),
            ),
        )

    auth_cols = {c["name"] for c in insp.get_columns("project_auth_config")}
    if "admin_panel_path" not in auth_cols:
        op.add_column(
            "project_auth_config",
            sa.Column("admin_panel_path", sa.Text(), nullable=True),
        )
    if "customer_login_path" not in auth_cols:
        op.add_column(
            "project_auth_config",
            sa.Column("customer_login_path", sa.Text(), nullable=True),
        )


def downgrade() -> None:
    conn = op.get_bind()
    insp = inspect(conn)

    project_cols = {c["name"] for c in insp.get_columns("projects")}
    if "runtime_invariants" in project_cols:
        op.drop_column("projects", "runtime_invariants")

    auth_cols = {c["name"] for c in insp.get_columns("project_auth_config")}
    if "customer_login_path" in auth_cols:
        op.drop_column("project_auth_config", "customer_login_path")
    if "admin_panel_path" in auth_cols:
        op.drop_column("project_auth_config", "admin_panel_path")
