CREATE TABLE IF NOT EXISTS harnessrl_schema_migrations (
  migration_id TEXT PRIMARY KEY,
  applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS harnessrl_runs (
  run_id TEXT PRIMARY KEY,
  case_id TEXT NOT NULL,
  workflow_id TEXT NOT NULL UNIQUE,
  workflow_run_id TEXT,
  status TEXT NOT NULL,
  stage TEXT NOT NULL,
  case_repo TEXT NOT NULL,
  run_dir TEXT NOT NULL,
  runtime_api_url TEXT NOT NULL,
  result JSONB,
  error JSONB,
  blocker JSONB,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS harnessrl_run_events (
  id BIGSERIAL PRIMARY KEY,
  run_id TEXT NOT NULL REFERENCES harnessrl_runs(run_id) ON DELETE CASCADE,
  status TEXT NOT NULL,
  stage TEXT NOT NULL,
  payload JSONB NOT NULL DEFAULT '{}'::jsonb,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS harnessrl_activity_results (
  run_id TEXT NOT NULL REFERENCES harnessrl_runs(run_id) ON DELETE CASCADE,
  activity_name TEXT NOT NULL,
  identity TEXT NOT NULL,
  output JSONB NOT NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (run_id, activity_name, identity)
);

CREATE INDEX IF NOT EXISTS idx_harnessrl_events_run_id ON harnessrl_run_events(run_id, id);
CREATE INDEX IF NOT EXISTS idx_harnessrl_runs_created_at ON harnessrl_runs(created_at DESC, run_id DESC);

INSERT INTO harnessrl_schema_migrations (migration_id)
VALUES ('0001_harnessrl_registry')
ON CONFLICT DO NOTHING;
