"""add version to admin_settings

Revision ID: 73647ca7796f
Revises: 63647ca7796e
Create Date: 2026-04-11 12:00:00.000000
"""

import os
import sys
from typing import Sequence, Union

import sqlalchemy as sa

from alembic import op

# Add alembic folder to path for utils import
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from utils import (
    batch_alter_table,
    get_qualified_table_name,
    migration_logger as logger,
    timed_step,
    table_exists as _table_exists,
)

# revision identifiers, used by Alembic.
revision: str = "73647ca7796f"
down_revision: Union[str, Sequence[str], None] = "63647ca7796e"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    """Add a schema version column to admin settings."""
    with timed_step("Add admin_settings.version"):
        if not _table_exists("admin_settings"):
            logger.warning("admin_settings table not found; skipping version migration")
            return

        with batch_alter_table("admin_settings") as batch_op:
            batch_op.add_column(
                sa.Column(
                    "version",
                    sa.Integer(),
                    nullable=False,
                    server_default=sa.text("1"),
                )
            )

        bind = op.get_bind()
        bind.execute(
            sa.text(f"UPDATE {get_qualified_table_name('admin_settings')} SET version = 1 WHERE version IS NULL")
        )
        logger.info("admin_settings.version added and initialized to 1")


def downgrade() -> None:
    """Remove the schema version column from admin settings."""
    with timed_step("Drop admin_settings.version"):
        if not _table_exists("admin_settings"):
            logger.warning("admin_settings table not found; skipping version downgrade")
            return

        with batch_alter_table("admin_settings") as batch_op:
            batch_op.drop_column("version")
