-- Queue outbound ActivityPub deliveries so API responses do not wait on
-- remote inbox latency and failed deliveries can be retried.

CREATE TABLE IF NOT EXISTS outgoing_deliveries (
  id TEXT PRIMARY KEY,
  user_id TEXT NOT NULL,
  inbox TEXT NOT NULL,
  activity_id TEXT NOT NULL,
  activity_json TEXT NOT NULL,
  attempts INTEGER NOT NULL DEFAULT 0,
  next_attempt_at TEXT,
  locked_until TEXT,
  delivered_at TEXT,
  failed_at TEXT,
  last_error TEXT,
  created_at TEXT NOT NULL,
  updated_at TEXT NOT NULL,
  UNIQUE(user_id, inbox, activity_id)
);

CREATE INDEX IF NOT EXISTS idx_outgoing_deliveries_due ON outgoing_deliveries(next_attempt_at, locked_until);
CREATE INDEX IF NOT EXISTS idx_outgoing_deliveries_user_time ON outgoing_deliveries(user_id, created_at DESC);
