CREATE TABLE IF NOT EXISTS inbox_raw (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  connector TEXT NOT NULL,
  received_at TEXT NOT NULL DEFAULT (datetime('now')),
  payload TEXT NOT NULL,
  status TEXT NOT NULL DEFAULT 'pending',
  parse_status TEXT NULL,
  error TEXT NULL
);

CREATE TABLE IF NOT EXISTS outbox_result (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  canonical_payload TEXT NOT NULL,
  status TEXT NOT NULL DEFAULT 'pending',
  dedupe_key TEXT NOT NULL,
  attempts INTEGER NOT NULL DEFAULT 0,
  next_attempt_at INTEGER NOT NULL DEFAULT 0,
  last_error TEXT NULL,
  created_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_outbox_result_dedupe_key
  ON outbox_result (dedupe_key);

CREATE TABLE IF NOT EXISTS delivery_log (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  outbox_id INTEGER NOT NULL,
  attempt INTEGER NOT NULL,
  status TEXT NOT NULL,
  response_code INTEGER NULL,
  response_body TEXT NULL,
  latency_ms INTEGER NULL,
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
  FOREIGN KEY(outbox_id) REFERENCES outbox_result(id)
);

CREATE TABLE IF NOT EXISTS instrument_config (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  instrument_id TEXT NOT NULL UNIQUE,
  connector TEXT NOT NULL,
  enabled INTEGER NOT NULL DEFAULT 1,
  config TEXT NULL
);

CREATE TABLE IF NOT EXISTS dead_letter (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  payload TEXT NOT NULL,
  reason TEXT NOT NULL,
  created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
