CREATE TABLE user_video_watch_sessions (
    id BIGSERIAL PRIMARY KEY,
    user_id BIGINT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
    content_kind VARCHAR(32) NOT NULL CHECK (content_kind IN ('lms_lesson', 'exam_prep_lesson')),
    content_id BIGINT NOT NULL,
    session_number INT NOT NULL CHECK (session_number > 0),
    video_duration_sec INT,
    max_position_sec INT NOT NULL DEFAULT 0 CHECK (max_position_sec >= 0),
    started_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    last_heartbeat_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    ended_at TIMESTAMPTZ,
    completed_at TIMESTAMPTZ,
    UNIQUE (user_id, content_kind, content_id, session_number)
);

CREATE INDEX idx_user_video_watch_sessions_user ON user_video_watch_sessions (user_id);
CREATE INDEX idx_user_video_watch_sessions_content ON user_video_watch_sessions (content_kind, content_id);
CREATE INDEX idx_user_video_watch_sessions_started_at ON user_video_watch_sessions (started_at);
