-- name: ExamPrepCreateUnitModule :one
INSERT INTO exam_prep.unit_modules (unit_id, name, description, thumbnail, icon, sort_order)
SELECT
    $1,
    $2,
    $3,
    $4,
    $5,
    coalesce((
        SELECT
            max(m.sort_order)
        FROM exam_prep.unit_modules m
        WHERE
            m.unit_id = $1), 0) + 1
RETURNING
    *;

-- name: ExamPrepGetUnitModuleByID :one
SELECT *
FROM exam_prep.unit_modules
WHERE id = $1;

-- name: ExamPrepListUnitModuleIDsByUnit :many
SELECT
    m.id
FROM exam_prep.unit_modules m
WHERE
    m.unit_id = $1
ORDER BY
    m.id;

-- name: ExamPrepListUnitModulesByUnit :many
SELECT
    COUNT(*) OVER () AS total_count,
    m.id,
    m.unit_id,
    m.name,
    m.description,
    m.thumbnail,
    m.icon,
    m.sort_order,
    m.created_at,
    m.updated_at
FROM exam_prep.unit_modules m
WHERE
    m.unit_id = $1
ORDER BY
    m.sort_order ASC,
    m.id ASC
LIMIT $2
OFFSET $3;

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

-- name: ExamPrepDeleteUnitModule :exec
DELETE FROM exam_prep.unit_modules
WHERE id = $1;
