"""add refresh tokens table

Revision ID: 0002_refresh_tokens
Revises: 0001_initial_schema
Create Date: 2026-05-17 00:00:01.000000
"""

import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

revision = "0002_refresh_tokens"
down_revision = "0001_initial_schema"
branch_labels = None
depends_on = None


def upgrade() -> None:
    connection = op.get_bind()
    inspector = sa.inspect(connection)

    if not inspector.has_table("refresh_tokens"):
        op.create_table(
            "refresh_tokens",
            sa.Column("user_id", postgresql.UUID(as_uuid=True), nullable=False),
            sa.Column("token_hash", sa.String(length=255), nullable=False),
            sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False),
            sa.Column("revoked_at", sa.DateTime(timezone=True), nullable=True),
            sa.Column("user_agent", sa.String(length=512), nullable=True),
            sa.Column("ip_address", sa.String(length=64), nullable=True),
            sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
            sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),
            sa.ForeignKeyConstraint(["user_id"], ["users.id"]),
            sa.PrimaryKeyConstraint("id"),
            sa.UniqueConstraint("token_hash"),
        )

    existing_indexes = {index["name"] for index in inspector.get_indexes("refresh_tokens")}
    user_index = op.f("ix_refresh_tokens_user_id")
    expires_index = op.f("ix_refresh_tokens_expires_at")
    if user_index not in existing_indexes:
        op.create_index(user_index, "refresh_tokens", ["user_id"], unique=False)
    if expires_index not in existing_indexes:
        op.create_index(expires_index, "refresh_tokens", ["expires_at"], unique=False)


def downgrade() -> None:
    connection = op.get_bind()
    inspector = sa.inspect(connection)
    if inspector.has_table("refresh_tokens"):
        existing_indexes = {index["name"] for index in inspector.get_indexes("refresh_tokens")}
        expires_index = op.f("ix_refresh_tokens_expires_at")
        user_index = op.f("ix_refresh_tokens_user_id")
        if expires_index in existing_indexes:
            op.drop_index(expires_index, table_name="refresh_tokens")
        if user_index in existing_indexes:
            op.drop_index(user_index, table_name="refresh_tokens")
        op.drop_table("refresh_tokens")
