-- Home Security Agent — observaties voor dashboard :8765 (schema agent.*)

CREATE SCHEMA IF NOT EXISTS agent;

CREATE TABLE IF NOT EXISTS agent.observation_runs (
  id              bigserial PRIMARY KEY,
  observed_at     timestamptz NOT NULL,
  total_checks    integer NOT NULL DEFAULT 0,
  failed_checks   integer NOT NULL DEFAULT 0,
  summary         jsonb NOT NULL DEFAULT '{}',
  decision        jsonb,
  created_at      timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS ix_agent_runs_observed
  ON agent.observation_runs (observed_at DESC);

CREATE TABLE IF NOT EXISTS agent.findings (
  id              bigserial PRIMARY KEY,
  run_id          bigint NOT NULL REFERENCES agent.observation_runs(id) ON DELETE CASCADE,
  kind            text NOT NULL,
  name            text NOT NULL,
  ok              boolean NOT NULL,
  detail          text,
  meta            jsonb NOT NULL DEFAULT '{}',
  created_at      timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS ix_agent_findings_run ON agent.findings (run_id);
CREATE INDEX IF NOT EXISTS ix_agent_findings_failed ON agent.findings (run_id, ok) WHERE NOT ok;

CREATE TABLE IF NOT EXISTS agent.incidents (
  id              bigserial PRIMARY KEY,
  run_id          bigint REFERENCES agent.observation_runs(id) ON DELETE SET NULL,
  fingerprint     text NOT NULL,
  severity        text NOT NULL,
  title           text NOT NULL,
  body            text,
  notified        boolean NOT NULL DEFAULT false,
  created_at      timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS ix_agent_incidents_created
  ON agent.incidents (created_at DESC);

CREATE INDEX IF NOT EXISTS ix_agent_incidents_fp
  ON agent.incidents (fingerprint, created_at DESC);

GRANT USAGE ON SCHEMA agent TO PUBLIC;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA agent TO PUBLIC;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA agent TO PUBLIC;
