"""Add opaque public tokens to business_plan_exports and lead_requests.

Sequential integer IDs in public URLs leak business volume (e.g. export_id=47
reveals ~47 PDFs sold). Opaque tokens hide this while keeping integer PKs for
internal use.
"""
import secrets


def up(conn):
    # Add token columns (nullable to allow backfill before NOT NULL constraint)
    conn.execute(
        "ALTER TABLE business_plan_exports ADD COLUMN token TEXT"
    )
    conn.execute(
        "ALTER TABLE lead_requests ADD COLUMN token TEXT"
    )

    # Backfill existing rows
    export_ids = [row[0] for row in conn.execute(
        "SELECT id FROM business_plan_exports WHERE token IS NULL"
    ).fetchall()]
    for export_id in export_ids:
        conn.execute(
            "UPDATE business_plan_exports SET token = ? WHERE id = ?",
            (secrets.token_urlsafe(16), export_id),
        )

    lead_ids = [row[0] for row in conn.execute(
        "SELECT id FROM lead_requests WHERE token IS NULL"
    ).fetchall()]
    for lead_id in lead_ids:
        conn.execute(
            "UPDATE lead_requests SET token = ? WHERE id = ?",
            (secrets.token_urlsafe(16), lead_id),
        )

    # Unique indexes for fast token lookups
    conn.execute(
        "CREATE UNIQUE INDEX IF NOT EXISTS"
        " idx_business_plan_exports_token ON business_plan_exports (token)"
    )
    conn.execute(
        "CREATE UNIQUE INDEX IF NOT EXISTS"
        " idx_lead_requests_token ON lead_requests (token)"
    )
