-- Empyrion EAH-style features. Three tables:
--
-- 1. empyrion_events — append-only log of unsolicited Event_* packages
--    streamed from the bridge. Powers the player-history view, chat log,
--    and the "what happened while I was away" overview.
--
-- 2. empyrion_inv_templates — operator-defined inventory kits (name +
--    JSON list of {itemId, count}). Click "Apply" on a player row to
--    drop the whole kit via Request_Player_AddItem fan-out.
--
-- 3. empyrion_known_players — projected from empyrion_events. Cached
--    last-seen / first-seen / login count for the players-list view so
--    we don't aggregate the events table on every refresh.
--
-- All tables are scoped by instance_id so two running empyrion instances
-- on the same agent (rare but allowed) keep separate state.

CREATE TABLE IF NOT EXISTS empyrion_events (
  id            BIGSERIAL PRIMARY KEY,
  instance_id   TEXT        NOT NULL,
  ts            TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  cmd           TEXT        NOT NULL,
  player_id     INTEGER,
  steam_id      TEXT,
  player_name   TEXT,
  playfield     TEXT,
  msg           TEXT,
  raw           JSONB
);
CREATE INDEX IF NOT EXISTS empyrion_events_instance_ts
  ON empyrion_events (instance_id, ts DESC);
CREATE INDEX IF NOT EXISTS empyrion_events_player_ts
  ON empyrion_events (player_id, ts DESC) WHERE player_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS empyrion_events_steam_ts
  ON empyrion_events (steam_id, ts DESC) WHERE steam_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS empyrion_events_cmd
  ON empyrion_events (instance_id, cmd, ts DESC);

CREATE TABLE IF NOT EXISTS empyrion_inv_templates (
  id            BIGSERIAL   PRIMARY KEY,
  name          TEXT        NOT NULL,
  description   TEXT        NOT NULL DEFAULT '',
  items         JSONB       NOT NULL DEFAULT '[]'::jsonb,
  -- items shape: [{ "itemId": 4307, "count": 1, "ammo": 0, "decay": 0 }, ...]
  created_at    TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at    TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS empyrion_inv_templates_name
  ON empyrion_inv_templates (name);

CREATE TABLE IF NOT EXISTS empyrion_known_players (
  instance_id   TEXT        NOT NULL,
  player_id     INTEGER     NOT NULL,
  steam_id      TEXT        NOT NULL DEFAULT '',
  player_name   TEXT        NOT NULL DEFAULT '',
  first_seen    TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  last_seen     TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  login_count   INTEGER     NOT NULL DEFAULT 0,
  last_playfield TEXT       NOT NULL DEFAULT '',
  notes         TEXT        NOT NULL DEFAULT '',
  PRIMARY KEY (instance_id, player_id)
);
CREATE INDEX IF NOT EXISTS empyrion_known_players_steam
  ON empyrion_known_players (steam_id) WHERE steam_id != '';
CREATE INDEX IF NOT EXISTS empyrion_known_players_lastseen
  ON empyrion_known_players (instance_id, last_seen DESC);
