-- name: ExamPrepCreateCatalogCourse :one
INSERT INTO exam_prep.catalog_courses (name, description, thumbnail, sort_order)
SELECT
    $1,
    $2,
    $3,
    coalesce((
        SELECT
            max(c.sort_order)
        FROM exam_prep.catalog_courses AS c), 0) + 1
RETURNING
    *;

-- name: ExamPrepGetCatalogCourseByID :one
SELECT *
FROM exam_prep.catalog_courses
WHERE id = $1;

-- name: ExamPrepListCatalogCourses :many
SELECT
    COUNT(*) OVER () AS total_count,
    c.id,
    c.name,
    c.description,
    c.thumbnail,
    c.sort_order,
    c.created_at,
    c.updated_at
FROM exam_prep.catalog_courses c
ORDER BY c.sort_order ASC, c.id ASC
LIMIT $1 OFFSET $2;

-- name: ExamPrepListAllCatalogCourseIDs :many
SELECT
    id
FROM exam_prep.catalog_courses
ORDER BY id;

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

-- name: ExamPrepDeleteCatalogCourse :exec
DELETE FROM exam_prep.catalog_courses
WHERE id = $1;
