-- name: CreateCourse :one
INSERT INTO courses (program_id, name, description, thumbnail, sort_order)
SELECT
    $1,
    $2,
    $3,
    $4,
    coalesce((
        SELECT
            max(c.sort_order)
        FROM courses c
        WHERE
            c.program_id = $1), 0) + 1
RETURNING
    *;

-- name: GetCourseByID :one
SELECT *
FROM courses
WHERE id = $1;

-- name: ListCourseIDsByProgram :many
SELECT
    c.id
FROM
    courses AS c
WHERE
    c.program_id = $1
ORDER BY
    c.id;

-- name: ListCoursesByProgramID :many
SELECT
    COUNT(*) OVER () AS total_count,
    c.id,
    c.program_id,
    c.name,
    c.description,
    c.thumbnail,
    c.sort_order,
    c.created_at,
    c.updated_at,
    (
        SELECT
            COUNT(*)::bigint
        FROM
            modules m
        WHERE
            m.course_id = c.id) AS module_count,
    (
        SELECT
            COUNT(*)::bigint
        FROM
            lessons l
            INNER JOIN modules m ON l.module_id = m.id
        WHERE
            m.course_id = c.id) AS lesson_count,
    (
        SELECT
            COUNT(*)::bigint
        FROM
            lms_practices p
        WHERE
            p.course_id = c.id) AS practice_count
FROM
    courses c
WHERE
    c.program_id = $1
ORDER BY
    c.sort_order ASC,
    c.id ASC
LIMIT $2 OFFSET $3;

-- name: UpdateCourse :one
UPDATE 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: DeleteCourse :exec
DELETE FROM courses
WHERE id = $1;
