-- Player Session Tracking for Retention Analytics
-- Phase 2 Feature: Track individual player sessions to calculate post-wipe retention

CREATE TABLE player_sessions (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    license_id UUID NOT NULL REFERENCES licenses(id) ON DELETE CASCADE,
    steam_id VARCHAR(20) NOT NULL,
    player_name VARCHAR(100) NOT NULL,
    session_start TIMESTAMPTZ NOT NULL,
    session_end TIMESTAMPTZ,
    duration_seconds INTEGER,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_player_sessions_license ON player_sessions(license_id);
CREATE INDEX idx_player_sessions_steam ON player_sessions(license_id, steam_id);
CREATE INDEX idx_player_sessions_start ON player_sessions(session_start DESC);
CREATE INDEX idx_player_sessions_steam_start ON player_sessions(license_id, steam_id, session_start DESC);

-- Index for retention queries (JOIN with wipe_history on date ranges)
CREATE INDEX idx_player_sessions_license_start_range ON player_sessions(license_id, session_start)
    WHERE session_start IS NOT NULL;

COMMENT ON TABLE player_sessions IS 'Individual player join/leave sessions for retention analytics';
COMMENT ON COLUMN player_sessions.duration_seconds IS 'Calculated when session_end is set (session_end - session_start)';
COMMENT ON INDEX idx_player_sessions_steam_start IS 'Optimizes "last session for steam_id" queries when player leaves';
