CREATE TABLE IF NOT EXISTS "workflow_runs" (
  "id" text PRIMARY KEY DEFAULT gen_random_uuid()::text NOT NULL,
  "user_id" text NOT NULL REFERENCES "users"("id") ON DELETE cascade,
  "workflow_id" text NOT NULL,
  "workflow_version" text NOT NULL,
  "status" text DEFAULT 'running' NOT NULL,
  "goal" text,
  "input" jsonb,
  "current_step_id" text,
  "progress_percent" integer DEFAULT 0 NOT NULL,
  "qscore_before" jsonb,
  "qscore_after" jsonb,
  "created_at" timestamp with time zone DEFAULT now() NOT NULL,
  "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
  "completed_at" timestamp with time zone
);
CREATE INDEX IF NOT EXISTS "workflow_runs_user_idx" ON "workflow_runs" ("user_id", "created_at");
CREATE INDEX IF NOT EXISTS "workflow_runs_workflow_idx" ON "workflow_runs" ("workflow_id");

CREATE TABLE IF NOT EXISTS "workflow_run_modules" (
  "id" text PRIMARY KEY DEFAULT gen_random_uuid()::text NOT NULL,
  "run_id" text NOT NULL REFERENCES "workflow_runs"("id") ON DELETE cascade,
  "module_id" text NOT NULL,
  "title" text NOT NULL,
  "status" text DEFAULT 'idle' NOT NULL,
  "service" text,
  "output_summary" text,
  "output" jsonb,
  "error" text,
  "started_at" timestamp with time zone,
  "completed_at" timestamp with time zone
);

CREATE TABLE IF NOT EXISTS "workflow_artifacts" (
  "id" text PRIMARY KEY DEFAULT gen_random_uuid()::text NOT NULL,
  "run_id" text NOT NULL REFERENCES "workflow_runs"("id") ON DELETE cascade,
  "module_id" text,
  "type" text NOT NULL,
  "title" text NOT NULL,
  "repo_path" text,
  "public_url" text,
  "metadata" jsonb,
  "created_at" timestamp with time zone DEFAULT now() NOT NULL
);

CREATE TABLE IF NOT EXISTS "workflow_events" (
  "id" text PRIMARY KEY DEFAULT gen_random_uuid()::text NOT NULL,
  "run_id" text NOT NULL REFERENCES "workflow_runs"("id") ON DELETE cascade,
  "user_id" text NOT NULL REFERENCES "users"("id") ON DELETE cascade,
  "type" text NOT NULL,
  "payload" jsonb,
  "created_at" timestamp with time zone DEFAULT now() NOT NULL
);
