"""Add oauth_grants table

Revision ID: q7o5l1m3n4
Revises: p6n4k0l2m3
"""
from alembic import op
import sqlalchemy as sa

revision = "q7o5l1m3n4"
down_revision = "p6n4k0l2m3"
branch_labels = None
depends_on = None


def upgrade():
    op.create_table(
        "oauth_grants",
        sa.Column("id", sa.Integer, primary_key=True, autoincrement=True),
        sa.Column("token", sa.String(128), unique=True, nullable=False),
        sa.Column("user_id", sa.Integer, sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),
        sa.Column("client_id", sa.String(64), nullable=False),
        sa.Column("issuer_session", sa.String(128), nullable=False),
        sa.Column("device_id", sa.String(128), nullable=True),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
        sa.Column("revoked_at", sa.DateTime(timezone=True), nullable=True),
    )
    op.create_index("ix_oauth_grant_token", "oauth_grants", ["token"], unique=True)
    op.create_index("ix_oauth_grant_issuer", "oauth_grants", ["issuer_session"])
    op.create_index("ix_oauth_grant_user", "oauth_grants", ["user_id"])
    op.create_index("ix_oauth_grant_device", "oauth_grants", ["device_id", "client_id"])

    # Add grant_token column to oauth_codes to link code → grant
    op.add_column("oauth_codes", sa.Column("grant_token", sa.String(128), nullable=True))


def downgrade():
    op.drop_column("oauth_codes", "grant_token")
    op.drop_index("ix_oauth_grant_user", table_name="oauth_grants")
    op.drop_index("ix_oauth_grant_issuer", table_name="oauth_grants")
    op.drop_index("ix_oauth_grant_token", table_name="oauth_grants")
    op.drop_table("oauth_grants")
