-- name: ExamPrepCreateUnit :one
INSERT INTO exam_prep.units (catalog_course_id, name, description, thumbnail, sort_order)
SELECT
    $1,
    $2,
    $3,
    $4,
    coalesce((
        SELECT
            max(u.sort_order)
        FROM exam_prep.units u
        WHERE
            u.catalog_course_id = $1), 0) + 1
RETURNING
    *;

-- name: ExamPrepGetUnitByID :one
SELECT *
FROM exam_prep.units
WHERE id = $1;

-- name: ExamPrepListUnitIDsByCatalogCourse :many
SELECT
    u.id
FROM exam_prep.units u
WHERE
    u.catalog_course_id = $1
ORDER BY
    u.id;

-- name: ExamPrepListUnitsByCatalogCourse :many
SELECT
    COUNT(*) OVER () AS total_count,
    u.id,
    u.catalog_course_id,
    u.name,
    u.description,
    u.thumbnail,
    u.sort_order,
    u.created_at,
    u.updated_at
FROM exam_prep.units u
WHERE
    u.catalog_course_id = $1
ORDER BY
    u.sort_order ASC,
    u.id ASC
LIMIT $2
OFFSET $3;

-- name: ExamPrepUpdateUnit :one
UPDATE exam_prep.units
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: ExamPrepDeleteUnit :exec
DELETE FROM exam_prep.units
WHERE id = $1;
