-- name: AddSubCoursePrerequisite :one
INSERT INTO sub_course_prerequisites (sub_course_id, prerequisite_sub_course_id)
VALUES ($1, $2)
RETURNING *;

-- name: RemoveSubCoursePrerequisite :exec
DELETE FROM sub_course_prerequisites
WHERE sub_course_id = $1 AND prerequisite_sub_course_id = $2;

-- name: GetSubCoursePrerequisites :many
SELECT
    p.id,
    p.sub_course_id,
    p.prerequisite_sub_course_id,
    p.created_at,
    sc.title AS prerequisite_title,
    sc.level AS prerequisite_level,
    sc.display_order AS prerequisite_display_order
FROM sub_course_prerequisites p
JOIN sub_courses sc ON sc.id = p.prerequisite_sub_course_id
WHERE p.sub_course_id = $1
ORDER BY sc.display_order;

-- name: GetSubCourseDependents :many
SELECT
    p.id,
    p.sub_course_id,
    p.prerequisite_sub_course_id,
    p.created_at,
    sc.title AS dependent_title,
    sc.level AS dependent_level
FROM sub_course_prerequisites p
JOIN sub_courses sc ON sc.id = p.sub_course_id
WHERE p.prerequisite_sub_course_id = $1
ORDER BY sc.display_order;

-- name: CountUnmetPrerequisites :one
SELECT COUNT(*)::bigint AS unmet_count
FROM sub_course_prerequisites p
WHERE p.sub_course_id = $1
  AND p.prerequisite_sub_course_id NOT IN (
      SELECT usp.sub_course_id
      FROM user_sub_course_progress usp
      WHERE usp.user_id = $2
        AND usp.status = 'COMPLETED'
  );

-- name: DeleteAllPrerequisitesForSubCourse :exec
DELETE FROM sub_course_prerequisites
WHERE sub_course_id = $1;
