"""add is_active to users and password_reset_tokens table

Revision ID: d8e4f1a2c3b5
Revises: c7d3f9a1e2b4
Create Date: 2026-05-02 00:30:00.000000

"""
from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision: str = "d8e4f1a2c3b5"
down_revision: Union[str, Sequence[str], None] = "c7d3f9a1e2b4"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def _has_column(table: str, column: str) -> bool:
    bind = op.get_bind()
    inspector = sa.inspect(bind)
    return column in [c["name"] for c in inspector.get_columns(table)]


def _has_table(table: str) -> bool:
    bind = op.get_bind()
    inspector = sa.inspect(bind)
    return inspector.has_table(table)


def upgrade() -> None:
    """Add is_active to users and create password_reset_tokens table."""
    if not _has_column("users", "is_active"):
        op.add_column(
            "users",
            sa.Column("is_active", sa.Boolean(), nullable=False, server_default=sa.text("true")),
        )

    if not _has_table("password_reset_tokens"):
        op.create_table(
            "password_reset_tokens",
            sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
            sa.Column("user_id", sa.String(length=255), nullable=False),
            sa.Column("token_hash", sa.String(length=255), nullable=False),
            sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False),
            sa.Column("used_at", sa.DateTime(timezone=True), nullable=True),
            sa.Column(
                "created_at",
                sa.DateTime(timezone=True),
                server_default=sa.func.now(),
                nullable=True,
            ),
            sa.PrimaryKeyConstraint("id"),
        )
        op.create_index(
            "ix_password_reset_tokens_user_id",
            "password_reset_tokens",
            ["user_id"],
            unique=False,
        )
        op.create_index(
            "ix_password_reset_tokens_token_hash",
            "password_reset_tokens",
            ["token_hash"],
            unique=True,
        )


def downgrade() -> None:
    """Remove is_active column and password_reset_tokens table."""
    if _has_table("password_reset_tokens"):
        try:
            op.drop_index("ix_password_reset_tokens_token_hash", table_name="password_reset_tokens")
        except Exception:  # noqa: BLE001
            pass
        try:
            op.drop_index("ix_password_reset_tokens_user_id", table_name="password_reset_tokens")
        except Exception:  # noqa: BLE001
            pass
        op.drop_table("password_reset_tokens")

    if _has_column("users", "is_active"):
        op.drop_column("users", "is_active")