"""refresh token anomaly context

Revision ID: 000000000013
Revises: 000000000011
Create Date: 2026-02-13

TM-011: Add network context tracking to refresh_tokens table for
stolen token detection via IP/UA anomaly detection.

Adds columns:
  - issued_ip: IP address when token was first issued
  - issued_user_agent: User agent when token was first issued
  - last_seen_ip: Most recent IP address for this token
  - last_seen_user_agent: Most recent user agent for this token
  - anomaly_state: Anomaly detection decision (none/alert/blocked)

All columns are nullable for backwards compatibility with existing tokens.
"""

from alembic import op

revision = "000000000013"
down_revision = "000000000012"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # Add network context columns to refresh_tokens table
    op.execute("""
        ALTER TABLE refresh_tokens
        ADD COLUMN IF NOT EXISTS issued_ip TEXT,
        ADD COLUMN IF NOT EXISTS issued_user_agent TEXT,
        ADD COLUMN IF NOT EXISTS last_seen_ip TEXT,
        ADD COLUMN IF NOT EXISTS last_seen_user_agent TEXT,
        ADD COLUMN IF NOT EXISTS anomaly_state TEXT;
    """)

    # Add index for anomaly_state to support security monitoring queries
    op.execute("""
        CREATE INDEX IF NOT EXISTS idx_refresh_tokens_anomaly_state
        ON refresh_tokens (anomaly_state)
        WHERE anomaly_state IS NOT NULL;
    """)


def downgrade() -> None:
    # Drop the anomaly state index
    op.execute("""
        DROP INDEX IF EXISTS idx_refresh_tokens_anomaly_state;
    """)

    # Remove network context columns
    op.execute("""
        ALTER TABLE refresh_tokens
        DROP COLUMN IF EXISTS issued_ip,
        DROP COLUMN IF EXISTS issued_user_agent,
        DROP COLUMN IF EXISTS last_seen_ip,
        DROP COLUMN IF EXISTS last_seen_user_agent,
        DROP COLUMN IF EXISTS anomaly_state;
    """)
