-- Collection items table queries

-- name: GetCollectionItem :one
SELECT item_id, collection_id, site_id, template_id, html_content, position, created_at, updated_at, last_edited_by
FROM collection_items 
WHERE item_id = sqlc.arg(item_id) AND collection_id = sqlc.arg(collection_id) AND site_id = sqlc.arg(site_id);

-- name: GetCollectionItems :many
SELECT item_id, collection_id, site_id, template_id, html_content, position, created_at, updated_at, last_edited_by
FROM collection_items 
WHERE collection_id = sqlc.arg(collection_id) AND site_id = sqlc.arg(site_id)
ORDER BY position ASC;

-- name: GetCollectionItemsWithTemplate :many
SELECT 
    ci.item_id, ci.collection_id, ci.site_id, ci.template_id, ci.html_content, ci.position, ci.created_at, ci.updated_at, ci.last_edited_by,
    ct.name as template_name, ct.html_template, ct.is_default
FROM collection_items ci
JOIN collection_templates ct ON ci.template_id = ct.template_id
WHERE ci.collection_id = sqlc.arg(collection_id) AND ci.site_id = sqlc.arg(site_id)
ORDER BY ci.position ASC;

-- name: GetMaxPosition :one
SELECT COALESCE(MAX(position), 0) as max_position
FROM collection_items 
WHERE collection_id = sqlc.arg(collection_id) AND site_id = sqlc.arg(site_id);

-- name: CreateCollectionItem :one
INSERT INTO collection_items (item_id, collection_id, site_id, template_id, html_content, position, last_edited_by)
VALUES (sqlc.arg(item_id), sqlc.arg(collection_id), sqlc.arg(site_id), sqlc.arg(template_id), sqlc.arg(html_content), sqlc.arg(position), sqlc.arg(last_edited_by))
RETURNING item_id, collection_id, site_id, template_id, html_content, position, created_at, updated_at, last_edited_by;

-- name: UpdateCollectionItem :one
UPDATE collection_items 
SET html_content = sqlc.arg(html_content), last_edited_by = sqlc.arg(last_edited_by)
WHERE item_id = sqlc.arg(item_id) AND collection_id = sqlc.arg(collection_id) AND site_id = sqlc.arg(site_id)
RETURNING item_id, collection_id, site_id, template_id, html_content, position, created_at, updated_at, last_edited_by;

-- name: UpdateCollectionItemPosition :exec
UPDATE collection_items 
SET position = sqlc.arg(position), updated_at = CURRENT_TIMESTAMP, last_edited_by = sqlc.arg(last_edited_by)
WHERE item_id = sqlc.arg(item_id) AND collection_id = sqlc.arg(collection_id) AND site_id = sqlc.arg(site_id);

-- name: ReorderCollectionItems :exec
UPDATE collection_items 
SET position = position + sqlc.arg(position_delta)
WHERE collection_id = sqlc.arg(collection_id) AND site_id = sqlc.arg(site_id) 
  AND position >= sqlc.arg(start_position);



-- name: DeleteCollectionItem :exec
DELETE FROM collection_items 
WHERE item_id = sqlc.arg(item_id) AND collection_id = sqlc.arg(collection_id) AND site_id = sqlc.arg(site_id);

-- name: DeleteCollectionItems :exec
DELETE FROM collection_items 
WHERE collection_id = sqlc.arg(collection_id) AND site_id = sqlc.arg(site_id);

