CREATE TABLE IF NOT EXISTS event_outbox (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  event_id TEXT NOT NULL UNIQUE,
  event_type TEXT NOT NULL,
  event_version INTEGER NOT NULL DEFAULT 1,
  producer_service TEXT NOT NULL,
  entity_type TEXT NOT NULL,
  entity_id TEXT NOT NULL,
  correlation_id TEXT NULL,
  routing_key TEXT NOT NULL,
  payload_json TEXT NOT NULL DEFAULT '{}',
  status TEXT NOT NULL,
  attempt_count INTEGER NOT NULL DEFAULT 0,
  last_error TEXT NULL,
  available_at TEXT NOT NULL,
  published_at TEXT NULL,
  created_at TEXT NOT NULL,
  updated_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS ix_event_outbox_event_id ON event_outbox (event_id);
CREATE INDEX IF NOT EXISTS ix_event_outbox_event_type ON event_outbox (event_type);
CREATE INDEX IF NOT EXISTS ix_event_outbox_status ON event_outbox (status);
CREATE INDEX IF NOT EXISTS ix_event_outbox_available_at ON event_outbox (available_at);
CREATE INDEX IF NOT EXISTS ix_event_outbox_entity_type ON event_outbox (entity_type);
CREATE INDEX IF NOT EXISTS ix_event_outbox_entity_id ON event_outbox (entity_id);

CREATE TABLE IF NOT EXISTS event_inbox (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  consumer_name TEXT NOT NULL,
  event_id TEXT NOT NULL,
  event_type TEXT NOT NULL,
  processed_at TEXT NOT NULL,
  status TEXT NOT NULL,
  notes TEXT NULL
);
CREATE INDEX IF NOT EXISTS ix_event_inbox_consumer_name ON event_inbox (consumer_name);
CREATE INDEX IF NOT EXISTS ix_event_inbox_event_id ON event_inbox (event_id);
CREATE INDEX IF NOT EXISTS ix_event_inbox_event_type ON event_inbox (event_type);
CREATE UNIQUE INDEX IF NOT EXISTS uq_event_inbox_consumer_event ON event_inbox (consumer_name, event_id);

CREATE TABLE IF NOT EXISTS reporting_event_log (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  event_id TEXT NOT NULL,
  event_type TEXT NOT NULL,
  queue_id TEXT NULL,
  channel TEXT NULL,
  interaction_id TEXT NULL,
  payload_json TEXT NOT NULL DEFAULT '{}',
  created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS ix_reporting_event_log_event_id ON reporting_event_log (event_id);
CREATE INDEX IF NOT EXISTS ix_reporting_event_log_event_type ON reporting_event_log (event_type);
CREATE INDEX IF NOT EXISTS ix_reporting_event_log_queue_id ON reporting_event_log (queue_id);
CREATE INDEX IF NOT EXISTS ix_reporting_event_log_channel ON reporting_event_log (channel);
CREATE INDEX IF NOT EXISTS ix_reporting_event_log_interaction_id ON reporting_event_log (interaction_id);
