-- name: CreateModule :one
INSERT INTO modules (program_id, course_id, name, description, icon, sort_order, publish_status, access_tier)
SELECT
    sqlc.arg('program_id'),
    sqlc.arg('course_id'),
    sqlc.arg('name'),
    sqlc.arg('description'),
    sqlc.arg('icon'),
    COALESCE(sqlc.narg('sort_order')::int,
        COALESCE((
            SELECT
                max(m.sort_order)
            FROM modules m
            WHERE
                m.course_id = sqlc.arg('course_id')), 0) + 1),
    sqlc.arg('publish_status'),
    sqlc.arg('access_tier')
RETURNING
    *;

-- name: GetModuleByID :one
SELECT
    m.*,
    EXISTS (
        SELECT 1
        FROM lms_practices p
        WHERE p.module_id = m.id
          AND p.lesson_id IS NULL
          AND p.publish_status = 'PUBLISHED'
    ) AS has_practice
FROM modules
    m
WHERE m.id = $1;

-- name: ListModuleIDsByCourse :many
SELECT
    m.id
FROM
    modules AS m
WHERE
    m.course_id = $1
ORDER BY
    m.id;

-- Published modules only, for learner-facing progress rollups.
-- name: ListPublishedModuleIDsByCourse :many
SELECT
    m.id
FROM
    modules AS m
WHERE
    m.course_id = $1
    AND m.publish_status = 'PUBLISHED'
ORDER BY
    m.id;

-- name: ListModulesByProgramAndCourse :many
SELECT
    COUNT(*) OVER () AS total_count,
    m.id,
    m.program_id,
    m.course_id,
    m.name,
    m.description,
    m.icon,
    m.sort_order,
    m.publish_status,
    m.access_tier,
    m.created_at,
    m.updated_at,
    EXISTS (
        SELECT 1
        FROM lms_practices p
        WHERE p.module_id = m.id
          AND p.lesson_id IS NULL
          AND p.publish_status = 'PUBLISHED'
    ) AS has_practice
FROM
    modules m
WHERE
    m.program_id = $1
    AND m.course_id = $2
    AND (
        sqlc.arg('published_only')::boolean = FALSE
        OR m.publish_status = 'PUBLISHED'::TEXT
    )
ORDER BY
    m.sort_order ASC,
    m.id ASC
LIMIT $3
OFFSET $4;

-- name: UpdateModule :one
UPDATE modules
SET
    name = COALESCE(sqlc.narg('name')::varchar, name),
    description = COALESCE(sqlc.narg('description')::text, description),
    icon = COALESCE(sqlc.narg('icon')::text, icon),
    sort_order = coalesce(sqlc.narg('sort_order')::int, sort_order),
    publish_status = COALESCE(sqlc.narg('publish_status')::varchar, publish_status),
    access_tier = COALESCE(sqlc.narg('access_tier')::varchar, access_tier),
    updated_at = CURRENT_TIMESTAMP
WHERE
    id = sqlc.arg('id')
RETURNING
    *;

-- name: DeleteModule :exec
DELETE FROM modules
WHERE id = $1;
