-- 002_spawns.sql — Prometheus generations + Spawn records (idempotent).
--
-- Backs the manual / approval-gated Pump.fun creator workflow (§10, §15):
--   prometheus_generations — every Spawn package Prometheus generates, with the
--     mixer input, the raw output, its review status, and the risk flags raised.
--   spawn_records          — the public, immutable record of a Spawn whose token
--     was MANUALLY created on Pump.fun by the operator (mint / metadata URI /
--     Pump.fun URL / launch tx). PYRE never signs the launch (§3) — it only
--     records it.
--
-- Safe to run repeatedly: every object uses IF NOT EXISTS. JSON columns are
-- JSONB; the TypeScript layer marshals them as parsed objects.

CREATE TABLE IF NOT EXISTS prometheus_generations (
  id              BIGSERIAL   PRIMARY KEY,
  -- The cleanup receipt this generation drew its burned-token context from.
  -- Nullable: a generation can be seeded from a minimal operator-supplied input
  -- with no backing receipt.
  receipt_id      BIGINT,
  input_json      JSONB       NOT NULL,
  output_json     JSONB       NOT NULL,
  status          TEXT        NOT NULL DEFAULT 'generated'
                    CHECK (status IN ('generated', 'approved', 'rejected', 'launched')),
  risk_flags_json JSONB       NOT NULL DEFAULT '[]',
  created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
  approved_at     TIMESTAMPTZ,
  rejected_at     TIMESTAMPTZ
);

CREATE TABLE IF NOT EXISTS spawn_records (
  id            BIGSERIAL   PRIMARY KEY,
  generation_id BIGINT      NOT NULL REFERENCES prometheus_generations(id),
  spawn_name    TEXT        NOT NULL,
  ticker        TEXT        NOT NULL,
  mint          TEXT,
  metadata_uri  TEXT,
  pumpfun_url   TEXT,
  launch_tx     TEXT,
  status        TEXT        NOT NULL DEFAULT 'launched'
                  CHECK (status IN ('launched', 'pending')),
  created_at    TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_prometheus_generations_receipt_id
  ON prometheus_generations (receipt_id);

CREATE INDEX IF NOT EXISTS idx_spawn_records_generation_id
  ON spawn_records (generation_id);
