"""create api_hub_credentials table

Revision ID: b4d6e8a0c2f4
Revises: a2c4e6f8b1d3
Create Date: 2026-05-03 08:00:00.000000

Creates the api_hub_credentials table that backs admin-editable provider
secrets in the API Hub. Encrypted values are stored as text blobs; the
unique (provider_id, name) constraint guarantees each env var has a
single canonical row per provider.
"""
from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision: str = "b4d6e8a0c2f4"
down_revision: Union[str, Sequence[str], None] = "a2c4e6f8b1d3"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def _has_table(table: str) -> bool:
    bind = op.get_bind()
    inspector = sa.inspect(bind)
    try:
        return inspector.has_table(table)
    except Exception:  # noqa: BLE001
        return False


def _safe_create_index(name: str, table: str, cols: list[str]) -> None:
    try:
        op.create_index(name, table, cols, unique=False)
    except Exception:  # noqa: BLE001
        pass


def upgrade() -> None:
    if not _has_table("api_hub_credentials"):
        op.create_table(
            "api_hub_credentials",
            sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
            sa.Column("provider_id", sa.String(length=64), nullable=False),
            sa.Column("name", sa.String(length=128), nullable=False),
            sa.Column("encrypted_value", sa.Text(), nullable=False),
            sa.Column("updated_by", sa.String(length=255), nullable=True),
            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.PrimaryKeyConstraint("id"),
            sa.UniqueConstraint(
                "provider_id", "name", name="uq_api_hub_credentials_provider_name"
            ),
        )
        _safe_create_index(
            "ix_api_hub_credentials_provider_id",
            "api_hub_credentials",
            ["provider_id"],
        )


def downgrade() -> None:
    if _has_table("api_hub_credentials"):
        try:
            op.drop_table("api_hub_credentials")
        except Exception:  # noqa: BLE001
            pass