-- IT0 Presence & Analytics Tables (public schema)
-- Telemetry event log, device profiles, DAU stats, online snapshots

CREATE TABLE IF NOT EXISTS presence_event_log (
    id            BIGSERIAL PRIMARY KEY,
    user_id       VARCHAR(36),
    install_id    VARCHAR(64) NOT NULL,
    event_name    VARCHAR(64) NOT NULL,
    event_time    TIMESTAMPTZ NOT NULL,
    device_brand  VARCHAR(64),
    device_model  VARCHAR(64),
    device_os     VARCHAR(32),
    app_version   VARCHAR(32),
    locale        VARCHAR(16),
    properties    JSONB,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_presence_event_log_event_time       ON presence_event_log (event_time);
CREATE INDEX IF NOT EXISTS idx_presence_event_log_event_name       ON presence_event_log (event_name);
CREATE INDEX IF NOT EXISTS idx_presence_event_log_event_name_time  ON presence_event_log (event_name, event_time);
CREATE INDEX IF NOT EXISTS idx_presence_event_log_user_id          ON presence_event_log (user_id);
CREATE INDEX IF NOT EXISTS idx_presence_event_log_device_brand     ON presence_event_log (device_brand);
CREATE INDEX IF NOT EXISTS idx_presence_event_log_app_version      ON presence_event_log (app_version);

CREATE TABLE IF NOT EXISTS presence_device_profile (
    install_id    VARCHAR(64) PRIMARY KEY,
    user_id       VARCHAR(36),
    device_brand  VARCHAR(64),
    device_model  VARCHAR(64),
    device_os     VARCHAR(32),
    app_version   VARCHAR(32),
    locale        VARCHAR(16),
    first_seen_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    last_seen_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    event_count   INTEGER NOT NULL DEFAULT 1
);

CREATE INDEX IF NOT EXISTS idx_presence_device_profile_brand       ON presence_device_profile (device_brand);
CREATE INDEX IF NOT EXISTS idx_presence_device_profile_app_version ON presence_device_profile (app_version);
CREATE INDEX IF NOT EXISTS idx_presence_device_profile_user_id     ON presence_device_profile (user_id);
CREATE INDEX IF NOT EXISTS idx_presence_device_profile_last_seen   ON presence_device_profile (last_seen_at DESC);

CREATE TABLE IF NOT EXISTS presence_daily_active_users (
    day             DATE PRIMARY KEY,
    dau_count       INTEGER NOT NULL,
    dau_by_province JSONB,
    dau_by_city     JSONB,
    calculated_at   TIMESTAMPTZ NOT NULL,
    version         INTEGER NOT NULL DEFAULT 1
);

CREATE TABLE IF NOT EXISTS presence_online_snapshots (
    id             BIGSERIAL PRIMARY KEY,
    ts             TIMESTAMPTZ NOT NULL UNIQUE,
    online_count   INTEGER NOT NULL,
    window_seconds INTEGER NOT NULL DEFAULT 300
);

CREATE INDEX IF NOT EXISTS idx_presence_online_snapshots_ts ON presence_online_snapshots (ts DESC);
