"""Plex playlists (Siftlode-native, per-user, ordered)

Revision ID: 0048_plex_playlists
Revises: 0047_plex_collections
Create Date: 2026-07-06

Per-user ORDERED watch-lists of Plex items, kept in Siftlode's own DB so they work for users without a
Plex account (like plex_states) — the "your own lists" counterpart to the shared, library-level
collections. `plex_playlists` is owned by a user; `plex_playlist_items` holds the ordered entries
(`position`). `plex_rating_key` is reserved for an optional later Plex-direction sync.
"""
from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

revision: str = "0048_plex_playlists"
down_revision: Union[str, None] = "0047_plex_collections"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.create_table(
        "plex_playlists",
        sa.Column("id", sa.Integer(), primary_key=True),
        sa.Column("user_id", sa.Integer(), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),
        sa.Column("title", sa.String(length=512), nullable=False),
        sa.Column("plex_rating_key", sa.String(length=32), nullable=True),
        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),
    )
    op.create_index("ix_plex_playlists_user_id", "plex_playlists", ["user_id"])

    op.create_table(
        "plex_playlist_items",
        sa.Column("id", sa.Integer(), primary_key=True),
        sa.Column(
            "playlist_id", sa.Integer(),
            sa.ForeignKey("plex_playlists.id", ondelete="CASCADE"), nullable=False,
        ),
        sa.Column(
            "item_id", sa.Integer(),
            sa.ForeignKey("plex_items.id", ondelete="CASCADE"), nullable=False,
        ),
        sa.Column("position", sa.Integer(), nullable=False, server_default="0"),
        sa.UniqueConstraint("playlist_id", "item_id", name="uq_plex_playlist_item"),
    )
    op.create_index("ix_plex_playlist_items_playlist_id", "plex_playlist_items", ["playlist_id"])
    op.create_index("ix_plex_playlist_items_item_id", "plex_playlist_items", ["item_id"])


def downgrade() -> None:
    op.drop_index("ix_plex_playlist_items_item_id", table_name="plex_playlist_items")
    op.drop_index("ix_plex_playlist_items_playlist_id", table_name="plex_playlist_items")
    op.drop_table("plex_playlist_items")
    op.drop_index("ix_plex_playlists_user_id", table_name="plex_playlists")
    op.drop_table("plex_playlists")
