-- name: ExamPrepCreateUnitModuleLesson :one
INSERT INTO exam_prep.unit_module_lessons (unit_module_id, title, video_url, thumbnail, description, sort_order)
SELECT
    $1,
    $2,
    $3,
    $4,
    $5,
    coalesce((
        SELECT
            max(l.sort_order)
        FROM exam_prep.unit_module_lessons l
        WHERE
            l.unit_module_id = $1), 0) + 1
RETURNING
    *;

-- name: ExamPrepGetUnitModuleLessonByID :one
SELECT
    l.*,
    EXISTS (
        SELECT 1
        FROM exam_prep.lesson_practices p
        WHERE p.unit_module_lesson_id = l.id
    ) AS has_practice
FROM exam_prep.unit_module_lessons l
WHERE l.id = $1;

-- name: ExamPrepListUnitModuleLessonIDsByUnitModule :many
SELECT
    l.id
FROM exam_prep.unit_module_lessons l
WHERE
    l.unit_module_id = $1
ORDER BY
    l.id;

-- name: ExamPrepListUnitModuleLessonsByUnitModuleID :many
SELECT
    COUNT(*) OVER () AS total_count,
    l.id,
    l.unit_module_id,
    l.title,
    l.video_url,
    l.thumbnail,
    l.description,
    l.sort_order,
    EXISTS (
        SELECT 1
        FROM exam_prep.lesson_practices p
        WHERE p.unit_module_lesson_id = l.id
    ) AS has_practice,
    l.created_at,
    l.updated_at
FROM exam_prep.unit_module_lessons l
WHERE
    l.unit_module_id = $1
ORDER BY
    l.sort_order ASC,
    l.id ASC
LIMIT $2
OFFSET $3;

-- name: ExamPrepUpdateUnitModuleLesson :one
UPDATE exam_prep.unit_module_lessons
SET
    title = coalesce(sqlc.narg('title')::varchar, title),
    video_url = coalesce(sqlc.narg('video_url')::text, video_url),
    thumbnail = coalesce(sqlc.narg('thumbnail')::text, thumbnail),
    description = coalesce(sqlc.narg('description')::text, description),
    sort_order = coalesce(sqlc.narg('sort_order')::int, sort_order),
    updated_at = CURRENT_TIMESTAMP
WHERE id = sqlc.arg('id')
RETURNING
    *;

-- name: ExamPrepDeleteUnitModuleLesson :exec
DELETE FROM exam_prep.unit_module_lessons
WHERE id = $1;
