-- Migration 006: Extension system tables
--
-- Extensions are installable plugins that add renderers, tools, surfaces,
-- and event handlers. Three tiers: browser (JS), starlark (sandbox),
-- sidecar (container). Browser tier ships first (v0.11.0).
--
-- See EXTENSIONS.md for full spec.

-- ── Extension registry ──────────────────────────

CREATE TABLE IF NOT EXISTS extensions (
    id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    ext_id      VARCHAR(100) NOT NULL UNIQUE,       -- manifest id (e.g. "collapsible-code")
    name        VARCHAR(200) NOT NULL,               -- human label
    version     VARCHAR(50)  NOT NULL DEFAULT '0.0.0',
    tier        VARCHAR(20)  NOT NULL DEFAULT 'browser',  -- browser | starlark | sidecar
    description TEXT         NOT NULL DEFAULT '',
    author      VARCHAR(200) NOT NULL DEFAULT '',
    manifest    JSONB        NOT NULL DEFAULT '{}',  -- full manifest JSON
    is_system   BOOLEAN      NOT NULL DEFAULT false, -- admin-pushed, users can't disable
    is_enabled  BOOLEAN      NOT NULL DEFAULT true,  -- global enable/disable
    scope       VARCHAR(20)  NOT NULL DEFAULT 'global', -- global | team | personal
    team_id     UUID         REFERENCES teams(id) ON DELETE CASCADE,
    installed_by UUID        REFERENCES users(id) ON DELETE SET NULL,
    created_at  TIMESTAMPTZ  NOT NULL DEFAULT now(),
    updated_at  TIMESTAMPTZ  NOT NULL DEFAULT now()
);

-- For bundled extensions that ship with core
CREATE INDEX IF NOT EXISTS idx_extensions_tier ON extensions(tier);
CREATE INDEX IF NOT EXISTS idx_extensions_enabled ON extensions(is_enabled) WHERE is_enabled = true;

-- ── Per-user extension settings ─────────────────

CREATE TABLE IF NOT EXISTS extension_user_settings (
    extension_id UUID NOT NULL REFERENCES extensions(id) ON DELETE CASCADE,
    user_id      UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    settings     JSONB   NOT NULL DEFAULT '{}',  -- user's config values
    is_enabled   BOOLEAN NOT NULL DEFAULT true,   -- per-user toggle
    PRIMARY KEY (extension_id, user_id)
);
