ALTER TABLE site_analytics_daily
  ADD COLUMN IF NOT EXISTS engaged_views INTEGER NOT NULL DEFAULT 0,
  ADD COLUMN IF NOT EXISTS total_engaged_seconds INTEGER NOT NULL DEFAULT 0;

ALTER TABLE post_analytics_daily
  ADD COLUMN IF NOT EXISTS engaged_views INTEGER NOT NULL DEFAULT 0,
  ADD COLUMN IF NOT EXISTS total_engaged_seconds INTEGER NOT NULL DEFAULT 0,
  ADD COLUMN IF NOT EXISTS scroll_25 INTEGER NOT NULL DEFAULT 0,
  ADD COLUMN IF NOT EXISTS scroll_50 INTEGER NOT NULL DEFAULT 0,
  ADD COLUMN IF NOT EXISTS scroll_75 INTEGER NOT NULL DEFAULT 0,
  ADD COLUMN IF NOT EXISTS scroll_100 INTEGER NOT NULL DEFAULT 0;

CREATE TABLE IF NOT EXISTS analytics_active_sessions (
  session_hash TEXT PRIMARY KEY,
  user_id UUID REFERENCES users(id) ON DELETE SET NULL,
  path TEXT NOT NULL,
  post_id UUID REFERENCES posts(id) ON DELETE SET NULL,
  post_slug TEXT NOT NULL DEFAULT '',
  first_seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  last_seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  duration_seconds INTEGER NOT NULL DEFAULT 0,
  max_scroll_ratio REAL NOT NULL DEFAULT 0
);

CREATE INDEX IF NOT EXISTS analytics_active_sessions_last_seen_idx
  ON analytics_active_sessions (last_seen_at DESC);

CREATE INDEX IF NOT EXISTS analytics_active_sessions_user_idx
  ON analytics_active_sessions (user_id)
  WHERE user_id IS NOT NULL;
