"""Add admin_2fa_sessions table

Revision ID: 014_add_admin_2fa
Revises: 013_add_admin_logs
Create Date: 2024-12-18

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy import inspect


# revision identifiers, used by Alembic.
revision: str = '014_add_admin_2fa'
down_revision: Union[str, None] = '013_add_admin_logs'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def table_exists(table_name: str) -> bool:
    bind = op.get_bind()
    inspector = inspect(bind)
    return table_name in inspector.get_table_names()


def index_exists(table_name: str, index_name: str) -> bool:
    bind = op.get_bind()
    inspector = inspect(bind)
    indexes = inspector.get_indexes(table_name)
    return any(idx['name'] == index_name for idx in indexes)


def upgrade() -> None:
    if not table_exists('admin_2fa_sessions'):
        op.create_table(
            'admin_2fa_sessions',
            sa.Column('id', sa.Integer(), primary_key=True),
            sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=False),
            sa.Column('code', sa.String(6), nullable=False),
            sa.Column('telegram_sent', sa.Boolean(), server_default='false', nullable=False),
            sa.Column('is_verified', sa.Boolean(), server_default='false', nullable=False),
            sa.Column('expires_at', sa.DateTime(), nullable=False),
            sa.Column('created_at', sa.DateTime(), server_default=sa.func.now(), nullable=False),
        )

    if not index_exists('admin_2fa_sessions', 'ix_admin_2fa_sessions_user_id'):
        op.create_index('ix_admin_2fa_sessions_user_id', 'admin_2fa_sessions', ['user_id'])
    if not index_exists('admin_2fa_sessions', 'ix_admin_2fa_sessions_expires_at'):
        op.create_index('ix_admin_2fa_sessions_expires_at', 'admin_2fa_sessions', ['expires_at'])


def downgrade() -> None:
    op.drop_index('ix_admin_2fa_sessions_expires_at', 'admin_2fa_sessions')
    op.drop_index('ix_admin_2fa_sessions_user_id', 'admin_2fa_sessions')
    op.drop_table('admin_2fa_sessions')
