-- 0006_fix_job_logs_fk.sql
--
-- Migration 0005 rebuilt the jobs table via the unsafe pattern of
-- renaming the original to jobs_old before dropping it. SQLite (with
-- legacy_alter_table=OFF, the modern default) propagated that rename
-- into the FK declaration of job_logs.job_id, which is now pointing
-- at jobs_old — a table that no longer exists. INSERTs into job_logs
-- fail with "no such table: main.jobs_old (1)".
--
-- Rebuild job_logs using the safe pattern: create job_logs_new with
-- a clean FK to jobs, copy rows, drop the broken job_logs, rename
-- job_logs_new to job_logs. Renaming job_logs_new is safe because
-- nothing references it.

PRAGMA foreign_keys = OFF;

CREATE TABLE job_logs_new (
  job_id      TEXT NOT NULL REFERENCES jobs(id) ON DELETE CASCADE,
  seq         INTEGER NOT NULL,
  ts          TEXT NOT NULL,
  stream      TEXT NOT NULL CHECK (stream IN ('stdout','stderr','event')),
  payload     TEXT NOT NULL,
  PRIMARY KEY (job_id, seq)
);

INSERT INTO job_logs_new (job_id, seq, ts, stream, payload)
  SELECT job_id, seq, ts, stream, payload FROM job_logs;

DROP TABLE job_logs;

ALTER TABLE job_logs_new RENAME TO job_logs;

PRAGMA foreign_keys = ON;
