-- name: CreateQuestion :one
INSERT INTO questions (
    question_text,
    question_type,
    difficulty_level,
    points,
    explanation,
    tips,
    voice_prompt,
    sample_answer_voice_prompt,
    status
)
VALUES ($1, $2, $3, COALESCE($4, 1), $5, $6, $7, $8, COALESCE($9, 'DRAFT'))
RETURNING *;

-- name: GetQuestionByID :one
SELECT *
FROM questions
WHERE id = $1;

-- name: GetQuestionsByIDs :many
SELECT *
FROM questions
WHERE id = ANY($1::BIGINT[])
ORDER BY id;

-- name: ListQuestions :many
SELECT
    COUNT(*) OVER () AS total_count,
    q.*
FROM questions q
WHERE status != 'ARCHIVED'
  AND ($1::VARCHAR IS NULL OR $1 = '' OR question_type = $1)
  AND ($2::VARCHAR IS NULL OR $2 = '' OR difficulty_level = $2)
  AND ($3::VARCHAR IS NULL OR $3 = '' OR status = $3)
ORDER BY created_at DESC
LIMIT sqlc.narg('limit')::INT
OFFSET sqlc.narg('offset')::INT;

-- name: SearchQuestions :many
SELECT
    COUNT(*) OVER () AS total_count,
    q.*
FROM questions q
WHERE status != 'ARCHIVED'
  AND question_text ILIKE '%' || $1 || '%'
ORDER BY created_at DESC
LIMIT sqlc.narg('limit')::INT
OFFSET sqlc.narg('offset')::INT;

-- name: UpdateQuestion :exec
UPDATE questions
SET
    question_text = COALESCE($1, question_text),
    question_type = COALESCE($2, question_type),
    difficulty_level = COALESCE($3, difficulty_level),
    points = COALESCE($4, points),
    explanation = COALESCE($5, explanation),
    tips = COALESCE($6, tips),
    voice_prompt = COALESCE($7, voice_prompt),
    sample_answer_voice_prompt = COALESCE($8, sample_answer_voice_prompt),
    status = COALESCE($9, status),
    updated_at = CURRENT_TIMESTAMP
WHERE id = $10;

-- name: ArchiveQuestion :exec
UPDATE questions
SET status = 'ARCHIVED', updated_at = CURRENT_TIMESTAMP
WHERE id = $1;

-- name: DeleteQuestion :exec
DELETE FROM questions
WHERE id = $1;

-- name: GetQuestionWithOptions :many
SELECT 
    q.id as question_id,
    q.question_text,
    q.question_type,
    q.difficulty_level,
    q.points,
    q.explanation,
    q.tips,
    q.voice_prompt,
    q.status,
    qo.id as option_id,
    qo.option_text,
    qo.option_order,
    qo.is_correct
FROM questions q
LEFT JOIN question_options qo ON qo.question_id = q.id
WHERE q.id = $1
ORDER BY qo.option_order;
