"""repo -> project bindings

Revision ID: 0064
Revises: 0063
Create Date: 2026-06-10

Maps a git repository (by its normalized remote, `repo_key`) to the Scribe
project it represents, so the SessionStart hook can resolve the active project
from the working repo instead of a project id pinned in plugin config. FKs
CASCADE so deleting a user or project removes the stale binding automatically.
"""
from alembic import op
import sqlalchemy as sa


revision = "0064"
down_revision = "0063"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        "repo_bindings",
        sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
        sa.Column(
            "user_id",
            sa.BigInteger(),
            sa.ForeignKey("users.id", ondelete="CASCADE"),
            nullable=False,
        ),
        sa.Column(
            "project_id",
            sa.BigInteger(),
            sa.ForeignKey("projects.id", ondelete="CASCADE"),
            nullable=False,
        ),
        sa.Column("repo_key", sa.Text(), nullable=False),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            server_default=sa.text("now()"),
            nullable=False,
        ),
        sa.Column(
            "updated_at",
            sa.DateTime(timezone=True),
            server_default=sa.text("now()"),
            nullable=False,
        ),
        sa.UniqueConstraint("user_id", "repo_key", name="uq_repo_bindings_user_repo"),
    )
    op.create_index("ix_repo_bindings_user_id", "repo_bindings", ["user_id"])


def downgrade() -> None:
    op.drop_index("ix_repo_bindings_user_id", table_name="repo_bindings")
    op.drop_table("repo_bindings")
