-- name: CreateCourse :one
INSERT INTO courses (
    category_id,
    title,
    description,
    thumbnail,
    intro_video_url,
    is_active
)
VALUES ($1, $2, $3, $4, $5, COALESCE($6, true))
RETURNING *;


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


-- name: GetCoursesByCategory :many
SELECT
    COUNT(*) OVER () AS total_count,
    id,
    category_id,
    title,
    description,
    thumbnail,
    intro_video_url,
    is_active
FROM courses
WHERE category_id = $1
ORDER BY display_order ASC, id ASC
LIMIT sqlc.narg('limit')::INT
OFFSET sqlc.narg('offset')::INT;

-- name: GetAllCourses :many
SELECT
    COUNT(*) OVER () AS total_count,
    c.id,
    c.category_id,
    c.sub_category_id,
    c.title,
    c.description,
    c.thumbnail,
    c.intro_video_url,
    c.is_active
FROM courses c
ORDER BY c.display_order ASC, c.id ASC
LIMIT sqlc.narg('limit')::INT
OFFSET sqlc.narg('offset')::INT;

-- name: GetHumanLanguageCourses :many
SELECT
    COUNT(*) OVER () AS total_count,
    c.id,
    c.category_id,
    c.sub_category_id,
    c.title,
    c.description,
    c.thumbnail,
    c.intro_video_url,
    c.is_active
FROM courses c
JOIN course_categories cc ON cc.id = c.category_id
WHERE lower(trim(cc.name)) = 'human language'
ORDER BY c.display_order ASC, c.id ASC
LIMIT sqlc.narg('limit')::INT
OFFSET sqlc.narg('offset')::INT;

-- name: GetCoursesBySubCategory :many
SELECT
    COUNT(*) OVER () AS total_count,
    c.id,
    c.category_id,
    c.sub_category_id,
    c.title,
    c.description,
    c.thumbnail,
    c.intro_video_url,
    c.is_active
FROM courses c
WHERE c.sub_category_id = $1
ORDER BY c.display_order ASC, c.id ASC
LIMIT sqlc.narg('limit')::INT
OFFSET sqlc.narg('offset')::INT;


-- name: UpdateCourse :exec
UPDATE courses
SET
    title = COALESCE($1, title),
    description = COALESCE($2, description),
    thumbnail = COALESCE($3, thumbnail),
    intro_video_url = COALESCE($4, intro_video_url),
    is_active = COALESCE($5, is_active)
WHERE id = $6;


-- name: DeleteCourse :exec
DELETE FROM courses
WHERE id = $1;

-- name: ReorderCourses :exec
UPDATE courses
SET display_order = bulk.position
FROM (
    SELECT unnest(@ids::BIGINT[]) AS id, unnest(@positions::INT[]) AS position
) AS bulk
WHERE courses.id = bulk.id;
