"""
add positions table

Revision ID: 20250922_add_positions
Revises: 20250921_align_schema_to_design
Create Date: 2025-09-22
"""

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


# revision identifiers, used by Alembic.
revision = "20250922_add_positions"
down_revision = "20250921_align_schema_to_design"
branch_labels = None
depends_on = None


def upgrade() -> None:
    bind = op.get_bind()
    inspector = inspect(bind)

    if not inspector.has_table("positions"):
        op.create_table(
            "positions",
            sa.Column("id", sa.Integer(), primary_key=True),
            sa.Column("name", sa.String(length=100), nullable=False),
            sa.Column("code", sa.String(length=100), nullable=False, unique=True),
            sa.Column("description", sa.Text(), nullable=True),
            sa.Column("parent_id", sa.Integer(), sa.ForeignKey("positions.id", ondelete="SET NULL"), nullable=True),
            sa.Column("status", sa.String(length=20), nullable=False, server_default="active"),
            sa.Column("is_deleted", sa.Boolean(), nullable=False, server_default=sa.false()),
            sa.Column("deleted_at", sa.DateTime(), nullable=True),
            sa.Column("created_by", sa.Integer(), nullable=True),
            sa.Column("updated_by", sa.Integer(), nullable=True),
            sa.Column("created_at", sa.DateTime(), nullable=False, server_default=sa.func.now()),
            sa.Column("updated_at", sa.DateTime(), nullable=False, server_default=sa.func.now()),
        )

    # 创建索引（若不存在）
    try:
        indexes = [ix.get("name") for ix in inspector.get_indexes("positions")]  # type: ignore
    except Exception:
        indexes = []
    if "ix_positions_name" not in indexes:
        op.create_index("ix_positions_name", "positions", ["name"], unique=False)


def downgrade() -> None:
    op.drop_index("ix_positions_name", table_name="positions")
    op.drop_table("positions")


