-- name: MarkPracticeCompleted :one
INSERT INTO user_practice_progress (
    user_id,
    sub_course_id,
    question_set_id,
    completed_at,
    updated_at
)
SELECT
    @user_id::BIGINT,
    qs.owner_id::BIGINT,
    qs.id,
    CURRENT_TIMESTAMP,
    CURRENT_TIMESTAMP
FROM question_sets qs
WHERE qs.id = @question_set_id::BIGINT
  AND qs.set_type = 'PRACTICE'
  AND qs.owner_type = 'SUB_COURSE'
  AND qs.status = 'PUBLISHED'
ON CONFLICT (user_id, question_set_id)
DO UPDATE SET
    completed_at = CURRENT_TIMESTAMP,
    updated_at = CURRENT_TIMESTAMP
RETURNING *;

-- name: GetFirstIncompletePreviousPractice :one
SELECT
    p.id,
    p.title,
    p.display_order
FROM question_sets target
JOIN question_sets p
    ON p.owner_type = 'SUB_COURSE'
   AND p.owner_id = target.owner_id
   AND p.set_type = 'PRACTICE'
   AND p.status = 'PUBLISHED'
   AND (
        p.display_order < target.display_order OR
        (p.display_order = target.display_order AND p.id < target.id)
   )
LEFT JOIN user_practice_progress upp
    ON upp.question_set_id = p.id
   AND upp.user_id = @user_id::BIGINT
   AND upp.completed_at IS NOT NULL
WHERE target.id = @question_set_id::BIGINT
  AND target.set_type = 'PRACTICE'
  AND target.owner_type = 'SUB_COURSE'
  AND target.status = 'PUBLISHED'
  AND upp.question_set_id IS NULL
ORDER BY p.display_order ASC, p.id ASC
LIMIT 1;
