"""Add admin_logs table

Revision ID: 013_add_admin_logs
Revises: 012_add_user_banned
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 = '013_add_admin_logs'
down_revision: Union[str, None] = '012_add_user_banned'
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_logs'):
        op.create_table(
            'admin_logs',
            sa.Column('id', sa.Integer(), primary_key=True),
            sa.Column('admin_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=False),
            sa.Column('action', sa.String(50), nullable=False),
            sa.Column('target_type', sa.String(50), nullable=False),
            sa.Column('target_id', sa.Integer(), nullable=False),
            sa.Column('details', sa.JSON(), nullable=True),
            sa.Column('ip_address', sa.String(50), nullable=True),
            sa.Column('created_at', sa.DateTime(), server_default=sa.func.now(), nullable=False),
        )

    if not index_exists('admin_logs', 'ix_admin_logs_admin_id'):
        op.create_index('ix_admin_logs_admin_id', 'admin_logs', ['admin_id'])
    if not index_exists('admin_logs', 'ix_admin_logs_action'):
        op.create_index('ix_admin_logs_action', 'admin_logs', ['action'])
    if not index_exists('admin_logs', 'ix_admin_logs_created_at'):
        op.create_index('ix_admin_logs_created_at', 'admin_logs', ['created_at'])


def downgrade() -> None:
    op.drop_index('ix_admin_logs_created_at', 'admin_logs')
    op.drop_index('ix_admin_logs_action', 'admin_logs')
    op.drop_index('ix_admin_logs_admin_id', 'admin_logs')
    op.drop_table('admin_logs')
