-- =============================================================================
-- Telemetry Service - Initial Schema
-- =============================================================================

-- 遥测事件流水表（append-only）
CREATE TABLE IF NOT EXISTS telemetry_events (
  id            BIGSERIAL PRIMARY KEY,
  user_id       UUID         NULL,
  install_id    VARCHAR(128) NOT NULL,
  event_name    VARCHAR(64)  NOT NULL,
  event_time    TIMESTAMPTZ  NOT NULL,
  properties    JSONB        NOT NULL DEFAULT '{}',
  created_at    TIMESTAMPTZ  NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_telemetry_events_name_time ON telemetry_events (event_name, event_time);
CREATE INDEX IF NOT EXISTS idx_telemetry_events_user_id   ON telemetry_events (user_id);
CREATE INDEX IF NOT EXISTS idx_telemetry_events_time      ON telemetry_events (event_time DESC);

-- 在线人数快照表（每分钟写入一次）
CREATE TABLE IF NOT EXISTS online_snapshots (
  id             BIGSERIAL   PRIMARY KEY,
  ts             TIMESTAMPTZ NOT NULL UNIQUE,
  online_count   INT         NOT NULL DEFAULT 0,
  window_seconds INT         NOT NULL DEFAULT 180
);

CREATE INDEX IF NOT EXISTS idx_online_snapshots_ts ON online_snapshots (ts DESC);

-- 日活统计汇总表
CREATE TABLE IF NOT EXISTS daily_active_stats (
  day             DATE        PRIMARY KEY,
  dau_count       INT         NOT NULL DEFAULT 0,
  dau_by_platform JSONB       NOT NULL DEFAULT '{}',
  dau_by_region   JSONB       NOT NULL DEFAULT '{}',
  calculated_at   TIMESTAMPTZ NOT NULL,
  version         INT         NOT NULL DEFAULT 1
);
