"""add local auth fields to users

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

"""
from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision: str = "c7d3f9a1e2b4"
down_revision: Union[str, Sequence[str], None] = "f4b0a6f99965"
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 upgrade() -> None:
    """Add password_hash and auth_provider columns; index email."""
    if not _has_column("users", "password_hash"):
        op.add_column("users", sa.Column("password_hash", sa.String(length=255), nullable=True))
    if not _has_column("users", "auth_provider"):
        op.add_column(
            "users",
            sa.Column("auth_provider", sa.String(length=50), nullable=False, server_default="platform"),
        )
    # Index on email for fast login lookup (ignore if already exists)
    try:
        op.create_index("ix_users_email", "users", ["email"], unique=False)
    except Exception:  # noqa: BLE001
        pass


def downgrade() -> None:
    """Remove local auth fields."""
    try:
        op.drop_index("ix_users_email", table_name="users")
    except Exception:  # noqa: BLE001
        pass
    if _has_column("users", "auth_provider"):
        op.drop_column("users", "auth_provider")
    if _has_column("users", "password_hash"):
        op.drop_column("users", "password_hash")