"""Add static_content table

Revision ID: 015_add_static_content
Revises: 014_add_admin_2fa
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 = '015_add_static_content'
down_revision: Union[str, None] = '014_add_admin_2fa'
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('static_content'):
        op.create_table(
            'static_content',
            sa.Column('id', sa.Integer(), primary_key=True),
            sa.Column('key', sa.String(100), unique=True, nullable=False),
            sa.Column('title', sa.String(200), nullable=False),
            sa.Column('content', sa.Text(), nullable=False),
            sa.Column('updated_by_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
            sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now(), nullable=False),
            sa.Column('created_at', sa.DateTime(), server_default=sa.func.now(), nullable=False),
        )

    if not index_exists('static_content', 'ix_static_content_key'):
        op.create_index('ix_static_content_key', 'static_content', ['key'], unique=True)


def downgrade() -> None:
    op.drop_index('ix_static_content_key', 'static_content')
    op.drop_table('static_content')
