-- ============================================================================
-- PostgreSQL initialization for StellaOps
-- This script runs automatically on first container start
-- ============================================================================

-- Enable pg_stat_statements extension for query performance analysis
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

-- Enable other useful extensions
CREATE EXTENSION IF NOT EXISTS pg_trgm;      -- Fuzzy text search
CREATE EXTENSION IF NOT EXISTS btree_gin;    -- GIN indexes for scalar types
CREATE EXTENSION IF NOT EXISTS pgcrypto;     -- Cryptographic functions

-- ============================================================================
-- Create schemas for all modules
-- Migrations will create tables within these schemas
-- ============================================================================

-- Core Platform
CREATE SCHEMA IF NOT EXISTS authority;     -- Authentication, authorization, OAuth/OIDC

-- Data Ingestion
CREATE SCHEMA IF NOT EXISTS vuln;          -- Concelier vulnerability data
CREATE SCHEMA IF NOT EXISTS vex;           -- Excititor VEX documents

-- Scanning & Analysis
CREATE SCHEMA IF NOT EXISTS scanner;       -- Container scanning, SBOM generation

-- Scheduling & Orchestration
CREATE SCHEMA IF NOT EXISTS scheduler;     -- Job scheduling
CREATE SCHEMA IF NOT EXISTS taskrunner;    -- Task execution

-- Policy & Risk
CREATE SCHEMA IF NOT EXISTS policy;        -- Policy engine
CREATE SCHEMA IF NOT EXISTS unknowns;      -- Unknown component tracking

-- Artifacts & Evidence
CREATE SCHEMA IF NOT EXISTS proofchain;    -- Attestor proof chains
CREATE SCHEMA IF NOT EXISTS attestor;      -- Attestor submission queue
CREATE SCHEMA IF NOT EXISTS signer;        -- Key management

-- Notifications
CREATE SCHEMA IF NOT EXISTS notify;        -- Notification delivery

-- Signals & Observability
CREATE SCHEMA IF NOT EXISTS signals;       -- Runtime signals

-- Registry
CREATE SCHEMA IF NOT EXISTS packs;         -- Task packs registry

-- Audit
CREATE SCHEMA IF NOT EXISTS audit;         -- System-wide audit log

-- ============================================================================
-- Grant usage to application user (for single-user mode)
-- Per-module users are created in 02-create-users.sql
-- ============================================================================
DO $$
DECLARE
    schema_name TEXT;
BEGIN
    FOR schema_name IN SELECT unnest(ARRAY[
        'authority', 'vuln', 'vex', 'scanner', 'scheduler', 'taskrunner',
        'policy', 'unknowns', 'proofchain', 'attestor', 'signer',
        'notify', 'signals', 'packs', 'audit'
    ]) LOOP
        EXECUTE format('GRANT USAGE ON SCHEMA %I TO PUBLIC', schema_name);
    END LOOP;
END $$;
