-- name: ExamPrepCreateUnit :one
INSERT INTO exam_prep.units (catalog_course_id, name, description, thumbnail, sort_order)
SELECT
    $1,
    $2,
    $3,
    $4,
    coalesce((
        SELECT
            max(u.sort_order)
        FROM exam_prep.units u
        WHERE
            u.catalog_course_id = $1), 0) + 1
RETURNING
    *;

-- name: ExamPrepGetUnitByID :one
SELECT *
FROM exam_prep.units
WHERE id = $1;

-- name: ExamPrepListUnitIDsByCatalogCourse :many
SELECT
    u.id
FROM exam_prep.units u
WHERE
    u.catalog_course_id = $1
ORDER BY
    u.id;

-- name: ExamPrepListUnitsByCatalogCourse :many
WITH unit_counts AS (
    SELECT
        u.id AS unit_id,
        COUNT(DISTINCT m.id)::BIGINT AS modules_count,
        COUNT(DISTINCT l.id)::BIGINT AS lessons_count,
        COUNT(DISTINCT p.id)::BIGINT AS practices_count
    FROM exam_prep.units u
    LEFT JOIN exam_prep.unit_modules m ON m.unit_id = u.id
    LEFT JOIN exam_prep.unit_module_lessons l ON l.unit_module_id = m.id
    LEFT JOIN exam_prep.lesson_practices p ON p.unit_module_lesson_id = l.id
    GROUP BY u.id
)
SELECT
    COUNT(*) OVER () AS total_count,
    u.id,
    u.catalog_course_id,
    u.name,
    u.description,
    u.thumbnail,
    u.sort_order,
    COALESCE(uc.modules_count, 0)::BIGINT AS modules_count,
    COALESCE(uc.lessons_count, 0)::BIGINT AS lessons_count,
    COALESCE(uc.practices_count, 0)::BIGINT AS practices_count,
    u.created_at,
    u.updated_at
FROM exam_prep.units u
LEFT JOIN unit_counts uc ON uc.unit_id = u.id
WHERE
    u.catalog_course_id = $1
ORDER BY
    u.sort_order ASC,
    u.id ASC
LIMIT $2
OFFSET $3;

-- name: ExamPrepUpdateUnit :one
UPDATE exam_prep.units
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: ExamPrepDeleteUnit :exec
DELETE FROM exam_prep.units
WHERE id = $1;
