CREATE EXTENSION IF NOT EXISTS pgcrypto; CREATE TABLE IF NOT EXISTS agents ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), tenant_id text NOT NULL, hostname text NOT NULL, api_key_hash char(64) NOT NULL, enabled boolean NOT NULL DEFAULT true, last_ip text NOT NULL DEFAULT '', first_seen timestamptz NOT NULL DEFAULT now(), last_seen timestamptz NOT NULL DEFAULT now(), UNIQUE (tenant_id, hostname) ); CREATE INDEX IF NOT EXISTS agents_last_seen_idx ON agents(tenant_id,last_seen DESC); CREATE TABLE IF NOT EXISTS detections ( id bigserial PRIMARY KEY, tenant_id text NOT NULL, fingerprint char(64) NOT NULL, rule_name text NOT NULL, severity text NOT NULL, status text NOT NULL DEFAULT 'open', hostname text NOT NULL DEFAULT '', user_name text NOT NULL DEFAULT '', source_ip text NOT NULL DEFAULT '', workstation text NOT NULL DEFAULT '', event_code integer NOT NULL DEFAULT 0, score double precision NOT NULL DEFAULT 0, window_start timestamptz NOT NULL, window_end timestamptz NOT NULL, summary text NOT NULL, hit_count bigint NOT NULL DEFAULT 1, first_seen timestamptz NOT NULL DEFAULT now(), last_seen timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), UNIQUE (tenant_id, fingerprint) ); CREATE INDEX IF NOT EXISTS detections_open_idx ON detections(tenant_id,status,last_seen DESC); CREATE INDEX IF NOT EXISTS detections_rule_idx ON detections(tenant_id,rule_name,last_seen DESC);