"""drop_clerk_columns

Drops Clerk-coupled schema in preparation for Better Auth:
- restaurant.owner_id (FK to user.id) + its index
- restaurant.subscription_plan (moves to organization.metadata.plan)
- user.clerk_id (column + unique index)

Pre-launch state: also TRUNCATEs the `user` table so the subsequent
`pnpm dlx auth migrate` step can ALTER `user` to ADD its NOT NULL
columns (name, emailVerified, image, createdAt, updatedAt) without
existing rows blocking the migration.

Deploy ordering — MANDATORY:
  1. uv run alembic upgrade head            (applies THIS revision)
  2. pnpm dlx auth migrate --config ...     (adds BA columns to user, etc.)
  3. uv run alembic upgrade head            (applies 0028+ which FK to team)

Revision ID: 0027_drop_clerk_columns
Revises: 0026_merge_rls_and_conversation_constraint
Create Date: 2026-05-22 17:30:00.000000
"""

from collections.abc import Sequence

from alembic import op

# revision identifiers, used by Alembic.
revision: str = "0027_drop_clerk_columns"
down_revision: str | None = "0026_merge_rls_and_conversation_constraint"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    # Drop restaurant.owner_id FK first (it pins user rows in place).
    op.drop_index("ix_restaurant_owner_id", table_name="restaurant")
    op.drop_constraint("restaurant_owner_id_fkey", "restaurant", type_="foreignkey")
    op.drop_column("restaurant", "owner_id")

    # subscription_plan moves to organization.metadata.plan (Better Auth org plugin).
    op.drop_column("restaurant", "subscription_plan")

    # Strip Clerk-coupled keys from restaurant.settings JSON. Idempotent — `?` no-ops
    # when the key isn't present.
    op.execute(
        """
        UPDATE restaurant
           SET settings = settings - 'clerk_organization_id' - 'clerk_memberships'
         WHERE settings ?| array['clerk_organization_id', 'clerk_memberships']
        """
    )

    # Drop user.clerk_id and its unique index. TRUNCATE user so Better Auth's
    # migrate step can ADD its NOT NULL columns. Pre-launch — no real users.
    # CASCADE because restaurant FK was already dropped above, but be defensive.
    op.execute('TRUNCATE TABLE "user" CASCADE')
    op.drop_index("ix_user_clerk_id", table_name="user")
    op.drop_column("user", "clerk_id")

    # Also drop full_name (orphan after BA owns `name`) and email + its
    # non-unique index. Better Auth re-adds `email` as UNIQUE NOT NULL via its
    # own migrate step; leaving the old non-unique index would silently allow
    # duplicate emails through.
    op.drop_column("user", "full_name")
    op.drop_index("ix_user_email", table_name="user")
    op.drop_column("user", "email")


def downgrade() -> None:
    # Pre-launch only — best-effort down-rev that recreates the column shape but
    # not data. Restoring rows is not supported.
    import sqlalchemy as sa  # noqa: PLC0415
    import sqlmodel  # noqa: PLC0415

    op.add_column(
        "user",
        sa.Column("clerk_id", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
    )
    op.create_index(op.f("ix_user_clerk_id"), "user", ["clerk_id"], unique=True)

    op.add_column(
        "restaurant",
        sa.Column(
            "subscription_plan",
            sqlmodel.sql.sqltypes.AutoString(),
            nullable=True,
        ),
    )
    op.add_column(
        "restaurant",
        sa.Column("owner_id", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
    )
    op.create_index(op.f("ix_restaurant_owner_id"), "restaurant", ["owner_id"], unique=False)
    op.create_foreign_key(
        "restaurant_owner_id_fkey",
        "restaurant",
        "user",
        ["owner_id"],
        ["id"],
    )
