"""Add share_token column to generated_shorts for public sharing.

Revision ID: 026_add_share_token
Revises: 025_add_generated_shorts
"""

import secrets

import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID

from alembic import op

revision = "026_add_share_token"
down_revision = "025_add_generated_shorts"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # Add nullable column first
    op.add_column(
        "generated_shorts",
        sa.Column("share_token", sa.String(16), nullable=True),
    )

    # Backfill existing complete shorts with unique tokens
    conn = op.get_bind()
    rows = conn.execute(
        sa.text("SELECT id FROM generated_shorts WHERE status = 'complete' AND share_token IS NULL")
    ).fetchall()
    for (row_id,) in rows:
        token = secrets.token_urlsafe(8)  # ~11 chars, fits in String(16)
        conn.execute(
            sa.text("UPDATE generated_shorts SET share_token = :token WHERE id = :id"),
            {"token": token, "id": row_id},
        )

    # Create unique index
    op.create_index("ix_generated_shorts_share_token", "generated_shorts", ["share_token"], unique=True)


def downgrade() -> None:
    op.drop_index("ix_generated_shorts_share_token", table_name="generated_shorts")
    op.drop_column("generated_shorts", "share_token")
