CREATE TABLE IF NOT EXISTS plugin_packages (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    name VARCHAR(100) NOT NULL,
    version VARCHAR(20) NOT NULL,
    description TEXT,
    publisher VARCHAR(200),
    source VARCHAR(20) NOT NULL,
    registry_url TEXT,
    wasm_sha256 VARCHAR(64) NOT NULL,
    wasm_bytes BYTEA NOT NULL,
    manifest JSONB NOT NULL,
    signature BYTEA,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE(name, version, publisher, wasm_sha256)
);

CREATE INDEX IF NOT EXISTS idx_plugin_packages_name ON plugin_packages(name);
CREATE INDEX IF NOT EXISTS idx_plugin_packages_created ON plugin_packages(created_at);

CREATE TABLE IF NOT EXISTS community_plugin_packages (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    community_id UUID NOT NULL REFERENCES communities(id) ON DELETE CASCADE,
    package_id UUID NOT NULL REFERENCES plugin_packages(id) ON DELETE CASCADE,
    installed_by UUID REFERENCES users(id) ON DELETE SET NULL,
    installed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    UNIQUE(community_id, package_id)
);

CREATE INDEX IF NOT EXISTS idx_community_plugin_packages_community ON community_plugin_packages(community_id);
CREATE INDEX IF NOT EXISTS idx_community_plugin_packages_installed_at ON community_plugin_packages(installed_at);
