-- Orchestration execution log.
-- Hver rad er ett kjørt steg (eller fallback) i en orkestrering.
-- Vaktmesteren logger hit under script-utførelse.

CREATE TABLE IF NOT EXISTS orchestration_log (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    orchestration_id UUID NOT NULL REFERENCES nodes(id) ON DELETE CASCADE,
    job_id          UUID REFERENCES job_queue(id) ON DELETE SET NULL,
    step_number     SMALLINT NOT NULL,       -- 0 = global fallback
    tool_binary     TEXT NOT NULL,            -- CLI-verktøy som ble kjørt
    args            JSONB NOT NULL DEFAULT '[]', -- argumenter (etter variabel-substitusjon)
    is_fallback     BOOLEAN NOT NULL DEFAULT false,
    status          TEXT NOT NULL CHECK (status IN ('ok', 'error', 'skipped')),
    exit_code       SMALLINT,                -- prosessens exit-kode
    result          JSONB,                   -- stdout JSON fra verktøyet
    error_msg       TEXT,                    -- stderr / feilmelding
    duration_ms     INTEGER,                 -- kjøretid i millisekunder
    created_at      TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX idx_orchestration_log_orch ON orchestration_log (orchestration_id, created_at DESC);
CREATE INDEX idx_orchestration_log_job ON orchestration_log (job_id);
