"""Add review_tokens table for anonymous reviewer access.

Revision ID: add_review_tokens
Revises: init_full_schema
Create Date: 2026-03-09 12:00:00.000000+00:00

Creates the review_tokens table for magic-link reviewer access.
Admins generate tokens that create anonymous user accounts on first click.
"""

from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision: str = "add_review_tokens"
down_revision: str = "init_full_schema"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    """Create review_tokens table with RLS."""
    op.create_table(
        "review_tokens",
        sa.Column(
            "token_hash",
            sa.Text(),
            nullable=False,
            comment="SHA-256 hash of the plaintext token",
        ),
        sa.Column(
            "label",
            sa.String(length=200),
            nullable=False,
            comment="Admin label, used as reviewer display name",
        ),
        sa.Column(
            "created_by_id",
            sa.UUID(),
            nullable=False,
            comment="Admin user who created this token",
        ),
        sa.Column(
            "expires_at",
            sa.DateTime(timezone=True),
            nullable=True,
            comment="When the token expires (null = no expiry)",
        ),
        sa.Column(
            "redeemed_at",
            sa.DateTime(timezone=True),
            nullable=True,
            comment="When the token was first redeemed",
        ),
        sa.Column(
            "redeemed_by_id",
            sa.UUID(),
            nullable=True,
            comment="Anonymous user created on first redemption",
        ),
        sa.Column(
            "is_active",
            sa.Boolean(),
            server_default="true",
            nullable=False,
            comment="Whether the token is active (admin can revoke)",
        ),
        sa.Column(
            "id",
            sa.UUID(),
            server_default=sa.text("uuidv7()"),
            nullable=False,
            comment="UUIDv7 primary key generated by PostgreSQL",
        ),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            server_default=sa.text("CURRENT_TIMESTAMP"),
            nullable=False,
            comment="Timestamp when record was created (UTC)",
        ),
        sa.Column(
            "updated_at",
            sa.DateTime(timezone=True),
            server_default=sa.text("CURRENT_TIMESTAMP"),
            nullable=False,
            comment="Timestamp when record was last updated (UTC)",
        ),
        sa.ForeignKeyConstraint(["created_by_id"], ["users.id"], ondelete="CASCADE"),
        sa.ForeignKeyConstraint(["redeemed_by_id"], ["users.id"], ondelete="SET NULL"),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index(
        op.f("ix_review_tokens_token_hash"),
        "review_tokens",
        ["token_hash"],
        unique=True,
    )

    # RLS: admin-only access (all operations go through get_admin_session)
    op.execute("ALTER TABLE review_tokens ENABLE ROW LEVEL SECURITY")
    op.execute("ALTER TABLE review_tokens FORCE ROW LEVEL SECURITY")
    op.execute(
        """
        CREATE POLICY review_tokens_admin ON review_tokens FOR ALL
            USING (current_user_is_admin())
    """
    )

    # Grant permissions to app and admin roles
    op.execute("GRANT ALL ON review_tokens TO openscientist_app")
    op.execute("GRANT ALL ON review_tokens TO openscientist_admin")


def downgrade() -> None:
    """Drop review_tokens table."""
    op.execute("DROP POLICY IF EXISTS review_tokens_admin ON review_tokens")
    op.drop_index(op.f("ix_review_tokens_token_hash"), table_name="review_tokens")
    op.drop_table("review_tokens")
