-- name: CreateQuestionSet :one
INSERT INTO question_sets (
    title,
    description,
    set_type,
    owner_type,
    owner_id,
    banner_image,
    persona,
    time_limit_minutes,
    passing_score,
    shuffle_questions,
    status,
    sub_course_video_id
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, COALESCE($10, false), COALESCE($11, 'DRAFT'), $12)
RETURNING *;

-- name: GetQuestionSetByID :one
SELECT *
FROM question_sets
WHERE id = $1;

-- name: GetQuestionSetsByOwner :many
SELECT *
FROM question_sets
WHERE owner_type = $1
  AND owner_id = $2
  AND status != 'ARCHIVED'
ORDER BY created_at DESC;

-- name: GetQuestionSetsByType :many
SELECT
    COUNT(*) OVER () AS total_count,
    qs.*
FROM question_sets qs
WHERE set_type = $1
  AND status != 'ARCHIVED'
ORDER BY created_at DESC
LIMIT sqlc.narg('limit')::INT
OFFSET sqlc.narg('offset')::INT;

-- name: GetPublishedQuestionSetsByOwner :many
SELECT *
FROM question_sets
WHERE owner_type = $1
  AND owner_id = $2
  AND status = 'PUBLISHED'
ORDER BY created_at DESC;

-- name: UpdateQuestionSet :exec
UPDATE question_sets
SET
    title = COALESCE($1, title),
    description = COALESCE($2, description),
    banner_image = COALESCE($3, banner_image),
    persona = COALESCE($4, persona),
    time_limit_minutes = COALESCE($5, time_limit_minutes),
    passing_score = COALESCE($6, passing_score),
    shuffle_questions = COALESCE($7, shuffle_questions),
    status = COALESCE($8, status),
    sub_course_video_id = COALESCE($9, sub_course_video_id),
    updated_at = CURRENT_TIMESTAMP
WHERE id = $10;

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

-- name: DeleteQuestionSet :exec
DELETE FROM question_sets
WHERE id = $1;

-- name: GetInitialAssessmentSet :one
SELECT *
FROM question_sets
WHERE set_type = 'INITIAL_ASSESSMENT'
  AND status = 'PUBLISHED'
ORDER BY created_at DESC
LIMIT 1;

-- name: AddUserPersonaToQuestionSet :one
INSERT INTO question_set_personas (
    question_set_id,
    user_id,
    display_order
)
VALUES ($1, $2, COALESCE($3, 0))
RETURNING *;

-- name: RemoveUserPersonaFromQuestionSet :exec
DELETE FROM question_set_personas
WHERE question_set_id = $1
  AND user_id = $2;

-- name: GetUserPersonasByQuestionSetID :many
SELECT
    u.id,
    u.first_name,
    u.last_name,
    u.nick_name,
    u.profile_picture_url,
    u.role,
    qsp.display_order
FROM users u
INNER JOIN question_set_personas qsp ON qsp.user_id = u.id
WHERE qsp.question_set_id = $1
ORDER BY qsp.display_order ASC;

-- name: UpdateQuestionSetVideoLink :exec
UPDATE question_sets
SET
    sub_course_video_id = $1,
    updated_at = CURRENT_TIMESTAMP
WHERE id = $2;
