-- name: StartSubCourseProgress :one
INSERT INTO user_sub_course_progress (user_id, sub_course_id)
VALUES ($1, $2)
ON CONFLICT (user_id, sub_course_id) DO NOTHING
RETURNING *;

-- name: UpdateSubCourseProgress :exec
UPDATE user_sub_course_progress
SET
    progress_percentage = $1,
    updated_at = CURRENT_TIMESTAMP
WHERE user_id = $2 AND sub_course_id = $3;

-- name: CompleteSubCourse :exec
UPDATE user_sub_course_progress
SET
    status = 'COMPLETED',
    progress_percentage = 100,
    completed_at = CURRENT_TIMESTAMP,
    updated_at = CURRENT_TIMESTAMP
WHERE user_id = $1 AND sub_course_id = $2;

-- name: GetUserSubCourseProgress :one
SELECT * FROM user_sub_course_progress
WHERE user_id = $1 AND sub_course_id = $2;

-- name: GetUserCourseProgress :many
SELECT
    usp.id,
    usp.user_id,
    usp.sub_course_id,
    usp.status,
    usp.progress_percentage,
    usp.started_at,
    usp.completed_at,
    usp.created_at,
    usp.updated_at,
    sc.title AS sub_course_title,
    sc.level AS sub_course_level,
    sc.display_order AS sub_course_display_order
FROM user_sub_course_progress usp
JOIN sub_courses sc ON sc.id = usp.sub_course_id
WHERE usp.user_id = $1 AND sc.course_id = $2
ORDER BY sc.display_order;

-- name: GetSubCoursesWithProgressByCourse :many
SELECT
    sc.id AS sub_course_id,
    sc.title,
    sc.description,
    sc.thumbnail,
    sc.display_order,
    sc.level,
    sc.is_active,
    COALESCE(usp.status, 'NOT_STARTED') AS progress_status,
    COALESCE(usp.progress_percentage, 0)::smallint AS progress_percentage,
    usp.started_at,
    usp.completed_at,
    (SELECT COUNT(*)::bigint
     FROM sub_course_prerequisites p
     WHERE p.sub_course_id = sc.id
       AND p.prerequisite_sub_course_id NOT IN (
           SELECT usp2.sub_course_id
           FROM user_sub_course_progress usp2
           WHERE usp2.user_id = $1
             AND usp2.status = 'COMPLETED'
       )
    ) AS unmet_prerequisites_count
FROM sub_courses sc
LEFT JOIN user_sub_course_progress usp
    ON usp.sub_course_id = sc.id AND usp.user_id = $1
WHERE sc.course_id = $2
  AND sc.is_active = true
ORDER BY sc.display_order;

-- name: DeleteUserSubCourseProgress :exec
DELETE FROM user_sub_course_progress
WHERE user_id = $1 AND sub_course_id = $2;
