"""add TOTP fields to auth_users and create auth_recovery_code table

Revision ID: 20260621_08_totp
Revises: 20260621_07_auth_login_throttle
Create Date: 2026-06-21 00:00:00.000000
"""

from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op


revision: str = "20260621_08_totp"
down_revision: Union[str, None] = "20260621_07_auth_login_throttle"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # Add totp_secret (nullable) to auth_users — existing rows get NULL, which is correct.
    op.add_column("auth_users", sa.Column("totp_secret", sa.String(length=64), nullable=True))
    # Add totp_enabled (NOT NULL) with server_default="0" so existing rows default to false.
    op.add_column(
        "auth_users",
        sa.Column(
            "totp_enabled",
            sa.Boolean(),
            nullable=False,
            server_default="0",
        ),
    )

    # Create auth_recovery_code table for one-time TOTP recovery codes.
    op.create_table(
        "auth_recovery_code",
        sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
        sa.Column("user_id", sa.Integer(), nullable=False),
        sa.Column("code_hash", sa.String(length=255), nullable=False),
        sa.Column("used_at", sa.DateTime(timezone=True), nullable=True),
        sa.ForeignKeyConstraint(["user_id"], ["auth_users.id"]),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index(
        op.f("ix_auth_recovery_code_user_id"),
        "auth_recovery_code",
        ["user_id"],
        unique=False,
    )


def downgrade() -> None:
    # Drop auth_recovery_code table first (has FK to auth_users).
    op.drop_index(op.f("ix_auth_recovery_code_user_id"), table_name="auth_recovery_code")
    op.drop_table("auth_recovery_code")

    # Drop the two TOTP columns from auth_users.
    # Use batch_alter_table for SQLite compatibility (alembic's portable column-drop path).
    with op.batch_alter_table("auth_users") as batch_op:
        batch_op.drop_column("totp_enabled")
        batch_op.drop_column("totp_secret")
