-- name: AddQuestionToSet :one
INSERT INTO question_set_items (
    set_id,
    question_id,
    display_order
)
VALUES ($1, $2, COALESCE($3, 0))
ON CONFLICT (set_id, question_id) DO UPDATE SET display_order = EXCLUDED.display_order
RETURNING *;

-- name: GetQuestionSetItems :many
SELECT 
    qsi.id,
    qsi.set_id,
    qsi.question_id,
    qsi.display_order,
    q.question_text,
    q.question_type,
    q.difficulty_level,
    q.points,
    q.explanation,
    q.tips,
    q.voice_prompt,
    q.status as question_status
FROM question_set_items qsi
JOIN questions q ON q.id = qsi.question_id
WHERE qsi.set_id = $1
  AND q.status != 'ARCHIVED'
ORDER BY qsi.display_order;

-- name: GetPublishedQuestionsInSet :many
SELECT 
    qsi.id,
    qsi.set_id,
    qsi.question_id,
    qsi.display_order,
    q.question_text,
    q.question_type,
    q.difficulty_level,
    q.points,
    q.explanation,
    q.tips,
    q.voice_prompt
FROM question_set_items qsi
JOIN questions q ON q.id = qsi.question_id
WHERE qsi.set_id = $1
  AND q.status = 'PUBLISHED'
ORDER BY qsi.display_order;

-- name: RemoveQuestionFromSet :exec
DELETE FROM question_set_items
WHERE set_id = $1 AND question_id = $2;

-- name: UpdateQuestionOrder :exec
UPDATE question_set_items
SET display_order = $1
WHERE set_id = $2 AND question_id = $3;

-- name: CountQuestionsInSet :one
SELECT COUNT(*) as count
FROM question_set_items qsi
JOIN questions q ON q.id = qsi.question_id
WHERE qsi.set_id = $1
  AND q.status != 'ARCHIVED';

-- name: GetQuestionSetsContainingQuestion :many
SELECT qs.*
FROM question_sets qs
JOIN question_set_items qsi ON qsi.set_id = qs.id
WHERE qsi.question_id = $1
  AND qs.status != 'ARCHIVED';
