-- ==========================================
-- Armature — 004 Connections & Dependencies
-- ==========================================

CREATE TABLE IF NOT EXISTS ext_connections (
    id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    type        TEXT NOT NULL,
    package_id  TEXT NOT NULL,
    scope       VARCHAR(10) NOT NULL
                CHECK (scope IN ('global', 'team', 'personal')),
    owner_id    TEXT NOT NULL DEFAULT '',
    name        TEXT NOT NULL,
    config      JSONB NOT NULL DEFAULT '{}'::jsonb,
    is_active   BOOLEAN DEFAULT true,
    created_at  TIMESTAMPTZ DEFAULT NOW(),
    updated_at  TIMESTAMPTZ DEFAULT NOW(),
    UNIQUE(type, scope, owner_id, name)
);

CREATE INDEX IF NOT EXISTS idx_ext_connections_type ON ext_connections(type);
CREATE INDEX IF NOT EXISTS idx_ext_connections_scope ON ext_connections(scope);
CREATE INDEX IF NOT EXISTS idx_ext_connections_owner ON ext_connections(owner_id) WHERE owner_id != '';
CREATE INDEX IF NOT EXISTS idx_ext_connections_active ON ext_connections(is_active) WHERE is_active = true;

DROP TRIGGER IF EXISTS ext_connections_updated_at ON ext_connections;
CREATE TRIGGER ext_connections_updated_at BEFORE UPDATE ON ext_connections
    FOR EACH ROW EXECUTE FUNCTION update_updated_at();

-- ── Extension Dependencies ──────────────────

CREATE TABLE IF NOT EXISTS ext_dependencies (
    consumer_id  TEXT NOT NULL,
    library_id   TEXT NOT NULL,
    version_spec TEXT NOT NULL DEFAULT '>=0.0.0',
    resolved_ver TEXT NOT NULL DEFAULT '0.0.0',
    PRIMARY KEY (consumer_id, library_id),
    FOREIGN KEY (consumer_id) REFERENCES packages(id) ON DELETE CASCADE,
    FOREIGN KEY (library_id)  REFERENCES packages(id) ON DELETE RESTRICT
);

CREATE INDEX IF NOT EXISTS idx_ext_deps_consumer ON ext_dependencies(consumer_id);
CREATE INDEX IF NOT EXISTS idx_ext_deps_library ON ext_dependencies(library_id);

-- ── Resource Grants ─────────────────────────

CREATE TABLE IF NOT EXISTS resource_grants (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    resource_type   VARCHAR(30) NOT NULL,
    resource_id     UUID NOT NULL,
    grant_scope     VARCHAR(20) NOT NULL DEFAULT 'team_only'
                    CHECK (grant_scope IN ('team_only', 'global', 'groups')),
    granted_groups  UUID[] NOT NULL DEFAULT '{}',
    created_by      UUID NOT NULL REFERENCES users(id),
    created_at      TIMESTAMPTZ DEFAULT NOW(),
    updated_at      TIMESTAMPTZ DEFAULT NOW(),
    UNIQUE(resource_type, resource_id)
);

CREATE INDEX IF NOT EXISTS idx_resource_grants_resource
    ON resource_grants(resource_type, resource_id);
CREATE INDEX IF NOT EXISTS idx_resource_grants_groups
    ON resource_grants USING gin(granted_groups);

DROP TRIGGER IF EXISTS resource_grants_updated_at ON resource_grants;
CREATE TRIGGER resource_grants_updated_at BEFORE UPDATE ON resource_grants
    FOR EACH ROW EXECUTE FUNCTION update_updated_at();
