"""public watch links for downloads (share-by-link)

Revision ID: 0042_download_links
Revises: 0041_download_edit
Create Date: 2026-07-04

A `download_links` row is a capability URL for one download: anyone holding the unguessable token
can watch the file on the public `/watch/{token}` player page — no account needed. Optional
per-link controls: an expiry, an "allow download" toggle, and an (argon2-hashed) password. Revoke
= delete the row. Distinct from `download_shares` (an ACL grant to another *registered* user).
"""
from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

revision: str = "0042_download_links"
down_revision: Union[str, None] = "0041_download_edit"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.create_table(
        "download_links",
        sa.Column("id", sa.Integer(), nullable=False),
        sa.Column("job_id", sa.Integer(), nullable=False),
        sa.Column("token", sa.String(length=64), nullable=False),
        sa.Column("created_by", sa.Integer(), nullable=True),
        sa.Column("allow_download", sa.Boolean(), server_default="false", nullable=False),
        sa.Column("password_hash", sa.Text(), nullable=True),
        sa.Column("expires_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("view_count", sa.Integer(), server_default="0", nullable=False),
        sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
        sa.ForeignKeyConstraint(["job_id"], ["download_jobs.id"], ondelete="CASCADE"),
        sa.ForeignKeyConstraint(["created_by"], ["users.id"], ondelete="CASCADE"),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint("token", name="uq_download_link_token"),
    )
    op.create_index("ix_download_links_job_id", "download_links", ["job_id"])


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