-- ==========================================
-- Chat Switchboard — 012 Extensions
-- ==========================================
-- Extension registry and per-user settings.
-- ICD §13 (Extensions)
-- ==========================================

-- =========================================
-- EXTENSIONS
-- =========================================

CREATE TABLE IF NOT EXISTS extensions (
    id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    ext_id      VARCHAR(100) NOT NULL UNIQUE,
    name        VARCHAR(200) NOT NULL,
    version     VARCHAR(50)  NOT NULL DEFAULT '0.0.0',
    tier        VARCHAR(20)  NOT NULL DEFAULT 'browser',
    description TEXT         NOT NULL DEFAULT '',
    author      VARCHAR(200) NOT NULL DEFAULT '',
    manifest    JSONB        NOT NULL DEFAULT '{}',
    is_system   BOOLEAN      NOT NULL DEFAULT false,
    is_enabled  BOOLEAN      NOT NULL DEFAULT true,
    scope       VARCHAR(20)  NOT NULL DEFAULT 'global',
    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()
);

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;


-- =========================================
-- EXTENSION USER 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 '{}',
    is_enabled   BOOLEAN NOT NULL DEFAULT true,
    PRIMARY KEY (extension_id, user_id)
);
