-- 0005_jobs_init_kind.sql
--
-- Add 'init' to the jobs.kind CHECK constraint so the operator can
-- dispatch a `restic init` job from the UI before the first backup.
-- SQLite can't ALTER a CHECK in place, so we rebuild the table.
--
-- Rebuild pattern note: we create jobs_new (with the wider CHECK),
-- copy data over, DROP the original jobs table, then ALTER RENAME
-- jobs_new TO jobs. This avoids the trap of renaming the original
-- first — with legacy_alter_table=OFF (the modern default), a rename
-- propagates into FK references in dependent tables (e.g.
-- job_logs.job_id), leaving them pointing at the temporary name even
-- after we drop it. Migration 0006 cleans up the orphan FK left by
-- the first version of this migration on already-affected DBs.

PRAGMA foreign_keys = OFF;

CREATE TABLE jobs_new (
  id              TEXT PRIMARY KEY,
  host_id         TEXT NOT NULL REFERENCES hosts(id) ON DELETE CASCADE,
  kind            TEXT NOT NULL CHECK (kind IN ('backup','init','forget','prune','check','unlock')),
  status          TEXT NOT NULL CHECK (status IN ('queued','running','succeeded','failed','cancelled')),
  scheduled_id    TEXT REFERENCES schedules(id) ON DELETE SET NULL,
  actor_kind      TEXT NOT NULL CHECK (actor_kind IN ('user','schedule','system')),
  actor_id        TEXT,
  started_at      TEXT,
  finished_at     TEXT,
  exit_code       INTEGER,
  stats           TEXT,
  error           TEXT,
  created_at      TEXT NOT NULL
);

INSERT INTO jobs_new
  SELECT id, host_id, kind, status, scheduled_id, actor_kind, actor_id,
         started_at, finished_at, exit_code, stats, error, created_at
  FROM jobs;

DROP TABLE jobs;

ALTER TABLE jobs_new RENAME TO jobs;

CREATE INDEX jobs_host_id ON jobs(host_id);
CREATE INDEX jobs_status ON jobs(status);
CREATE INDEX jobs_created_at ON jobs(created_at);

PRAGMA foreign_keys = ON;
