-- Phase 4.3 — LogLift event-log ingestion pipeline.
--
-- Extends rmm_executions to support B2-uploaded payloads (separate transport
-- from Overshell stdout) and rmm_settings to cache the LogLift component uid.
--
-- transport='overshell_stdout' (default for existing rows) — payload comes
-- back via Datto getJobResults stdout. The Phase 4.2 path.
-- transport='b2_upload' — collector script uploads gzipped JSON to B2 and
-- POSTs a webhook; Pulse downloads + parses asynchronously.

ALTER TABLE rmm_executions
  ADD COLUMN IF NOT EXISTS transport TEXT NOT NULL DEFAULT 'overshell_stdout'
    CHECK (transport IN ('overshell_stdout','b2_upload')),
  ADD COLUMN IF NOT EXISTS evidence_object_key TEXT,
  ADD COLUMN IF NOT EXISTS run_id TEXT;

-- Used to correlate inbound webhooks to a Pulse-dispatched execution.
CREATE UNIQUE INDEX IF NOT EXISTS ux_rmm_executions_run_id
  ON rmm_executions (run_id) WHERE run_id IS NOT NULL;

CREATE INDEX IF NOT EXISTS ix_rmm_executions_object_key
  ON rmm_executions (evidence_object_key) WHERE evidence_object_key IS NOT NULL;

ALTER TABLE rmm_settings
  ADD COLUMN IF NOT EXISTS loglift_component_uid TEXT,
  ADD COLUMN IF NOT EXISTS loglift_component_name TEXT,
  ADD COLUMN IF NOT EXISTS loglift_discovered_at TIMESTAMPTZ;

COMMENT ON COLUMN rmm_executions.transport IS
  'overshell_stdout (default) — Phase 4.2 path; payload arrives in Datto job stdout. '
  'b2_upload — Phase 4.3 LogLift; collector uploads gzipped JSON to Backblaze B2 '
  'and POSTs a webhook. Pulse downloads + parses async.';

COMMENT ON COLUMN rmm_executions.evidence_object_key IS
  'B2 object key for transport=b2_upload rows. Format: '
  '{datto_site_uid}/{computer_name}/eventlogs_{timestamp}.json.gz. '
  'Full payload stays in B2 (encrypted, signed-URL access only); '
  'parsed_evidence holds a slimmed view.';

COMMENT ON COLUMN rmm_executions.run_id IS
  'Collector-supplied correlation token. Used by the receiver to match an '
  'inbound webhook to a Pulse-dispatched execution. NULL for out-of-band '
  'collector runs.';
