-- name: CreateLesson :one
INSERT INTO lessons (module_id, title, video_url, thumbnail, description, sort_order, publish_status, access_tier)
SELECT
    sqlc.arg('module_id'),
    sqlc.arg('title'),
    sqlc.arg('video_url'),
    sqlc.arg('thumbnail'),
    sqlc.arg('description'),
    COALESCE(sqlc.narg('sort_order')::int,
        COALESCE((
            SELECT
                max(l.sort_order)
            FROM lessons l
            WHERE
                l.module_id = sqlc.arg('module_id')), 0) + 1),
    sqlc.arg('publish_status'),
    sqlc.arg('access_tier')
RETURNING
    *;

-- name: GetLessonByID :one
SELECT
    l.*,
    EXISTS (
        SELECT 1
        FROM lms_practices p
        WHERE p.lesson_id = l.id
          AND p.publish_status = 'PUBLISHED'
    ) AS has_practice
FROM lessons
    l
WHERE l.id = $1;

-- name: ListLessonIDsByModule :many
SELECT
    l.id
FROM
    lessons AS l
WHERE
    l.module_id = $1
ORDER BY
    l.id;

-- name: ListLessonsByModuleID :many
SELECT
    COUNT(*) OVER () AS total_count,
    l.id,
    l.module_id,
    l.title,
    l.video_url,
    l.thumbnail,
    l.description,
    l.sort_order,
    l.publish_status,
    l.access_tier,
    l.created_at,
    l.updated_at,
    EXISTS (
        SELECT 1
        FROM lms_practices p
        WHERE p.lesson_id = l.id
          AND p.publish_status = 'PUBLISHED'
    ) AS has_practice
FROM
    lessons l
WHERE
    l.module_id = $1
    AND (
        sqlc.arg('published_only')::boolean = FALSE
        OR l.publish_status = 'PUBLISHED'::TEXT
    )
ORDER BY
    l.sort_order ASC,
    l.id ASC
LIMIT $2
OFFSET $3;

-- name: UpdateLesson :one
UPDATE lessons
SET
    title = COALESCE(sqlc.narg('title')::varchar, title),
    video_url = COALESCE(sqlc.narg('video_url')::text, video_url),
    thumbnail = COALESCE(sqlc.narg('thumbnail')::text, thumbnail),
    description = COALESCE(sqlc.narg('description')::text, description),
    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: DeleteLesson :exec
DELETE FROM lessons
WHERE id = $1;
