"""Make discord_configs global (drop project_id) and add FK on channel_mappings.project_id.

Revision ID: 0002
Revises: 0001
"""

from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

revision: str = "0002"
down_revision: Union[str, None] = "0001"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


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

    # -- discord_configs: drop project_id column --
    conn.execute(sa.text("DROP INDEX IF EXISTS idx_discord_configs_project_id"))
    conn.execute(sa.text("ALTER TABLE discord_configs DROP COLUMN IF EXISTS project_id"))

    # -- discord_channel_mappings: replace project_id TEXT with proper FK --
    # Drop old project_id column (TEXT, no FK)
    conn.execute(sa.text(
        "ALTER TABLE discord_channel_mappings DROP COLUMN IF EXISTS project_id"
    ))
    # Re-add with NOT NULL FK to projects
    conn.execute(sa.text(
        "ALTER TABLE discord_channel_mappings "
        "ADD COLUMN project_id TEXT NOT NULL DEFAULT '' REFERENCES projects(id)"
    ))
    conn.execute(sa.text(
        "CREATE INDEX IF NOT EXISTS idx_discord_channel_mappings_project_id "
        "ON discord_channel_mappings(project_id)"
    ))


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

    # Restore project_id on discord_configs
    conn.execute(sa.text(
        "ALTER TABLE discord_configs ADD COLUMN project_id TEXT NOT NULL DEFAULT ''"
    ))
    conn.execute(sa.text(
        "CREATE INDEX idx_discord_configs_project_id ON discord_configs(project_id)"
    ))

    # Revert channel_mappings FK
    conn.execute(sa.text("DROP INDEX IF EXISTS idx_discord_channel_mappings_project_id"))
    conn.execute(sa.text(
        "ALTER TABLE discord_channel_mappings DROP COLUMN IF EXISTS project_id"
    ))
    conn.execute(sa.text(
        "ALTER TABLE discord_channel_mappings ADD COLUMN project_id TEXT NOT NULL DEFAULT ''"
    ))
