"""provision interfaces

Revision ID: 070_provision_interfaces
Revises: 069_payment_plugins
Create Date: 2026-06-24
"""

from alembic import op
import sqlalchemy as sa


revision = "070_provision_interfaces"
down_revision = "069_payment_plugins"
branch_labels = None
depends_on = None


def _table_exists(bind: sa.engine.Connection, table_name: str) -> bool:
    return table_name in set(sa.inspect(bind).get_table_names())


def _column_names(bind: sa.engine.Connection, table_name: str) -> set[str]:
    return {column["name"] for column in sa.inspect(bind).get_columns(table_name)}


def _index_names(bind: sa.engine.Connection, table_name: str) -> set[str]:
    return {index["name"] for index in sa.inspect(bind).get_indexes(table_name)}


def upgrade() -> None:
    bind = op.get_bind()
    if not _table_exists(bind, "provision_interfaces"):
        op.create_table(
            "provision_interfaces",
            sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
            sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
            sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
            sa.Column("name", sa.String(length=120), nullable=False),
            sa.Column("plugin_id", sa.String(length=80), nullable=False),
            sa.Column("config", sa.JSON(), nullable=True),
            sa.Column("enabled", sa.Boolean(), nullable=False, server_default=sa.true()),
            sa.Column("sort_order", sa.Integer(), nullable=False, server_default="0"),
            sa.Column("remark", sa.Text(), nullable=True),
            sa.Column("last_test_ok", sa.Boolean(), nullable=True),
            sa.Column("last_test_message", sa.String(length=255), nullable=True),
            sa.PrimaryKeyConstraint("id"),
        )
        op.create_index("ix_provision_interfaces_plugin_id", "provision_interfaces", ["plugin_id"])
        op.create_index("ix_provision_interfaces_enabled", "provision_interfaces", ["enabled"])

    if _table_exists(bind, "products"):
        columns = _column_names(bind, "products")
        if "provision_interface_id" not in columns:
            op.add_column("products", sa.Column("provision_interface_id", sa.Integer(), nullable=True))
        indexes = _index_names(bind, "products")
        if "ix_products_provision_interface_id" not in indexes:
            op.create_index("ix_products_provision_interface_id", "products", ["provision_interface_id"])
        if bind.dialect.name != "sqlite":
            try:
                op.create_foreign_key(
                    "fk_products_provision_interface_id",
                    "products",
                    "provision_interfaces",
                    ["provision_interface_id"],
                    ["id"],
                    ondelete="SET NULL",
                )
            except Exception:
                pass


def downgrade() -> None:
    bind = op.get_bind()
    if _table_exists(bind, "products"):
        indexes = _index_names(bind, "products")
        if "ix_products_provision_interface_id" in indexes:
            op.drop_index("ix_products_provision_interface_id", table_name="products")
        columns = _column_names(bind, "products")
        if "provision_interface_id" in columns:
            op.drop_column("products", "provision_interface_id")
    if _table_exists(bind, "provision_interfaces"):
        op.drop_index("ix_provision_interfaces_enabled", table_name="provision_interfaces")
        op.drop_index("ix_provision_interfaces_plugin_id", table_name="provision_interfaces")
        op.drop_table("provision_interfaces")
