"""T03: plugins + plugin_migrations tables.

Revision ID: 0003_plugin_system
Revises: 0002_contacts_fts
Create Date: 2026-06-29
"""

from __future__ import annotations

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

revision: str = "0003_plugin_system"
down_revision: Union[str, None] = "0002_contacts_fts"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # --- plugins table (system-wide, NOT tenant-scoped) ---
    op.create_table(
        "plugins",
        sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
        sa.Column("name", sa.String(80), nullable=False, unique=True),
        sa.Column("display_name", sa.String(120), nullable=False),
        sa.Column("version", sa.String(40), nullable=False),
        sa.Column("status", sa.String(20), nullable=False, server_default="installed"),
        sa.Column("installed", sa.Boolean, nullable=False, server_default=sa.text("true")),
        sa.Column("active", sa.Boolean, nullable=False, server_default=sa.text("false")),
        sa.Column("config", sa.Text, nullable=True),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
        sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
    )
    op.create_index("ix_plugins_name", "plugins", ["name"], unique=True)

    # --- plugin_migrations table (tracks which migrations have been applied) ---
    op.create_table(
        "plugin_migrations",
        sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
        sa.Column("plugin_name", sa.String(80), nullable=False),
        sa.Column("migration_file", sa.String(255), nullable=False),
        sa.Column("status", sa.String(20), nullable=False, server_default="applied"),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
        sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
        sa.UniqueConstraint("plugin_name", "migration_file", name="ix_plugin_migrations_unique"),
    )
    op.create_index("ix_plugin_migrations_plugin", "plugin_migrations", ["plugin_name"])


def downgrade() -> None:
    op.drop_table("plugin_migrations")
    op.drop_table("plugins")
