-- name: GetActiveVideoWatchSession :one
SELECT
    id,
    user_id,
    content_kind,
    content_id,
    session_number,
    video_duration_sec,
    max_position_sec,
    started_at,
    last_heartbeat_at,
    ended_at,
    completed_at
FROM user_video_watch_sessions
WHERE user_id = $1
    AND content_kind = $2
    AND content_id = $3
    AND ended_at IS NULL
    AND last_heartbeat_at >= $4
ORDER BY session_number DESC
LIMIT 1;

-- name: GetMaxVideoWatchSessionNumber :one
SELECT
    coalesce(max(session_number), 0)::int AS max_session_number
FROM user_video_watch_sessions
WHERE user_id = $1
    AND content_kind = $2
    AND content_id = $3;

-- name: InsertVideoWatchSession :one
INSERT INTO user_video_watch_sessions (
    user_id,
    content_kind,
    content_id,
    session_number,
    video_duration_sec,
    max_position_sec
)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING
    id,
    user_id,
    content_kind,
    content_id,
    session_number,
    video_duration_sec,
    max_position_sec,
    started_at,
    last_heartbeat_at,
    ended_at,
    completed_at;

-- name: UpdateVideoWatchSession :one
UPDATE user_video_watch_sessions
SET
    max_position_sec = $2,
    video_duration_sec = $3,
    last_heartbeat_at = $4,
    completed_at = $5,
    ended_at = $6
WHERE id = $1
RETURNING
    id,
    user_id,
    content_kind,
    content_id,
    session_number,
    video_duration_sec,
    max_position_sec,
    started_at,
    last_heartbeat_at,
    ended_at,
    completed_at;
