-- name: CreateSubCourseVideo :one
INSERT INTO sub_course_videos (
    sub_course_id,
    title,
    description,
    video_url,
    duration,
    resolution,
    instructor_id,
    thumbnail,
    visibility,
    display_order,
    status,
    vimeo_id,
    vimeo_embed_url,
    vimeo_player_html,
    vimeo_status,
    video_host_provider
)
VALUES (
    $1, $2, $3, $4, $5, $6,
    $7, $8, $9,
    COALESCE($10, 0),
    COALESCE($11, 'DRAFT'),
    $12, $13, $14,
    COALESCE($15, 'pending'),
    COALESCE($16, 'DIRECT')
)
RETURNING *;

-- name: GetSubCourseVideoByID :one
SELECT *
FROM sub_course_videos
WHERE id = $1;

-- name: GetVideosBySubCourse :many
SELECT
    COUNT(*) OVER () AS total_count,
    id,
    sub_course_id,
    title,
    description,
    video_url,
    duration,
    resolution,
    is_published,
    publish_date,
    visibility,
    instructor_id,
    thumbnail,
    display_order,
    status,
    vimeo_id,
    vimeo_embed_url,
    vimeo_player_html,
    vimeo_status,
    video_host_provider
FROM sub_course_videos
WHERE sub_course_id = $1
  AND status != 'ARCHIVED'
ORDER BY display_order ASC, id ASC;

-- name: GetPublishedVideosBySubCourse :many
SELECT *
FROM sub_course_videos
WHERE sub_course_id = $1
  AND status = 'PUBLISHED'
ORDER BY display_order ASC, publish_date ASC;

-- name: PublishSubCourseVideo :exec
UPDATE sub_course_videos
SET
    is_published = true,
    publish_date = CURRENT_TIMESTAMP,
    status = 'PUBLISHED'
WHERE id = $1;

-- name: UpdateSubCourseVideo :exec
UPDATE sub_course_videos
SET
    title = COALESCE($1, title),
    description = COALESCE($2, description),
    video_url = COALESCE($3, video_url),
    duration = COALESCE($4, duration),
    resolution = COALESCE($5, resolution),
    visibility = COALESCE($6, visibility),
    thumbnail = COALESCE($7, thumbnail),
    display_order = COALESCE($8, display_order),
    status = COALESCE($9, status),
    vimeo_id = COALESCE($10, vimeo_id),
    vimeo_embed_url = COALESCE($11, vimeo_embed_url),
    vimeo_player_html = COALESCE($12, vimeo_player_html),
    vimeo_status = COALESCE($13, vimeo_status),
    video_host_provider = COALESCE($14, video_host_provider)
WHERE id = $15;

-- name: UpdateVimeoStatus :exec
UPDATE sub_course_videos
SET
    vimeo_status = $1
WHERE id = $2;

-- name: GetVideosByVimeoID :one
SELECT * FROM sub_course_videos
WHERE vimeo_id = $1;

-- name: ArchiveSubCourseVideo :exec
UPDATE sub_course_videos
SET status = 'ARCHIVED'
WHERE id = $1;

-- name: DeleteSubCourseVideo :exec
DELETE FROM sub_course_videos
WHERE id = $1;

-- name: ReorderSubCourseVideos :exec
UPDATE sub_course_videos
SET display_order = bulk.position
FROM (
    SELECT unnest(@ids::BIGINT[]) AS id, unnest(@positions::INT[]) AS position
) AS bulk
WHERE sub_course_videos.id = bulk.id;
