"""Add is_core boolean column to plugins table.

Marks core plugins (permissions, entity_links, tags) as is_core=True so they
cannot be deactivated and are always loaded first.

Revision ID: 0016_plugin_is_core
Revises: 0015_rls_policies
Create Date: 2026-07-07
"""

from __future__ import annotations

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = "0016_plugin_is_core"
down_revision: Union[str, None] = "0015_rls_policies"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


CORE_PLUGIN_NAMES = ["permissions", "entity_links", "tags"]


def upgrade() -> None:
    # Add is_core column with server default False so existing rows get False
    op.add_column(
        "plugins",
        sa.Column("is_core", sa.Boolean(), nullable=False, server_default=sa.text("false")),
    )

    # Mark known core plugins as is_core=True
    op.execute(
        sa.text(
            "UPDATE plugins SET is_core = true WHERE name IN :names"
        ).bindparams(sa.bindparam("names", expanding=True)).bindparams(names=CORE_PLUGIN_NAMES)
    )


def downgrade() -> None:
    op.drop_column("plugins", "is_core")
