"""plex_link: per-user Plex account link for two-way watch-state sync

Phase A of the Plex ↔ Siftlode watch-state sync. One row per Siftlode user who syncs their watch
state with a Plex account. The owner MVP uses the server admin token (uses_admin=True, no personal
token); a personal token column is reserved for later friend-account linking (PIN OAuth). See the
PlexLink model docstring.
"""
from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

revision: str = "0051_plex_link"
down_revision: Union[str, None] = "0050_asset_poster"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.create_table(
        "plex_link",
        sa.Column("id", sa.Integer(), primary_key=True),
        sa.Column(
            "user_id",
            sa.Integer(),
            sa.ForeignKey("users.id", ondelete="CASCADE"),
            nullable=False,
        ),
        sa.Column("uses_admin", sa.Boolean(), server_default="true", nullable=False),
        sa.Column("plex_token_enc", sa.Text(), nullable=True),
        sa.Column("plex_account_id", sa.Integer(), nullable=True),
        sa.Column("plex_username", sa.String(length=255), nullable=True),
        sa.Column("sync_enabled", sa.Boolean(), server_default="false", nullable=False),
        sa.Column("initial_import_done", sa.Boolean(), server_default="false", nullable=False),
        sa.Column("last_watch_sync_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("linked_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column(
            "updated_at",
            sa.DateTime(timezone=True),
            server_default=sa.text("now()"),
            nullable=False,
        ),
        sa.UniqueConstraint("user_id", name="uq_plex_link_user"),
    )
    op.create_index("ix_plex_link_user_id", "plex_link", ["user_id"])


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