-- name: CreateProgram :one
INSERT INTO programs (name, description, category, thumbnail, sort_order)
SELECT
    sqlc.arg('name'),
    sqlc.arg('description'),
    sqlc.arg('category'),
    sqlc.arg('thumbnail'),
    COALESCE(sqlc.narg('sort_order')::int, COALESCE((
        SELECT
            max(p.sort_order)
        FROM programs AS p), 0) + 1)
RETURNING
    *;

-- name: GetProgramByID :one
SELECT *
FROM programs
WHERE id = $1;

-- name: ListAllProgramIDs :many
SELECT
    p.id
FROM
    programs AS p
ORDER BY
    p.id;

-- name: ListPrograms :many
SELECT
    COUNT(*) OVER () AS total_count,
    p.id,
    p.name,
    p.description,
    p.category,
    p.thumbnail,
    p.sort_order,
    p.created_at,
    p.updated_at
FROM programs p
ORDER BY p.sort_order ASC, p.id ASC
LIMIT $1 OFFSET $2;

-- name: UpdateProgram :one
UPDATE programs
SET
    name = COALESCE(sqlc.narg('name')::varchar, name),
    description = COALESCE(sqlc.narg('description')::text, description),
    category = COALESCE(sqlc.narg('category')::varchar, category),
    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: DeleteProgram :exec
DELETE FROM programs
WHERE id = $1;
