PRAGMA foreign_keys=OFF;

CREATE TABLE IF NOT EXISTS build_drafts_new (
  id TEXT PRIMARY KEY,
  template_id INTEGER,
  manifest_id TEXT NOT NULL DEFAULT '',
  source TEXT NOT NULL DEFAULT 'ui',
  request_name TEXT NOT NULL DEFAULT '',
  global_data_json BLOB,
  field_values_json BLOB,
  draft_context_json BLOB,
  status TEXT NOT NULL DEFAULT 'draft',
  notes TEXT NOT NULL DEFAULT '',
  created_at TEXT NOT NULL,
  updated_at TEXT NOT NULL,
  FOREIGN KEY (template_id) REFERENCES qc_templates(id) ON DELETE RESTRICT
);

INSERT INTO build_drafts_new (
  id, template_id, manifest_id, source, request_name, global_data_json,
  field_values_json, draft_context_json, status, notes, created_at, updated_at
)
SELECT
  id, template_id, manifest_id, source, request_name, global_data_json,
  field_values_json, NULL, status, notes, created_at, updated_at
FROM build_drafts;

DROP TABLE build_drafts;
ALTER TABLE build_drafts_new RENAME TO build_drafts;

CREATE INDEX IF NOT EXISTS idx_drafts_updated_at ON build_drafts(updated_at DESC);

PRAGMA foreign_keys=ON;
