-- name: CreateCourse :one
INSERT INTO courses (program_id, name, description, thumbnail, sort_order)
SELECT
    sqlc.arg('program_id'),
    sqlc.arg('name'),
    sqlc.arg('description'),
    sqlc.arg('thumbnail'),
    COALESCE(sqlc.narg('sort_order')::int,
        COALESCE((
            SELECT
                max(c.sort_order)
            FROM courses c
            WHERE
                c.program_id = sqlc.arg('program_id')), 0) + 1)
RETURNING
    *;

-- name: GetCourseByID :one
SELECT
    c.*,
    EXISTS (
        SELECT 1
        FROM lms_practices p
        WHERE p.course_id = c.id
          AND p.module_id IS NULL
          AND p.lesson_id IS NULL
    ) AS has_practice
FROM courses
    c
WHERE c.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,
    -- Practices whose parent is the course only (lms_practices.course_id). Excludes
    -- practices linked via module_id or lesson_id, even for modules/lessons in this course.
    (
        SELECT
            COUNT(*)::bigint
        FROM
            lms_practices p
        WHERE
            p.course_id = c.id
            AND p.module_id IS NULL
            AND p.lesson_id IS NULL) AS practice_count,
    EXISTS (
        SELECT 1
        FROM lms_practices p
        WHERE p.course_id = c.id
          AND p.module_id IS NULL
          AND p.lesson_id IS NULL
    ) AS has_practice
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;
