-- Collection item versions table queries

-- name: CreateCollectionItemVersion :exec
INSERT INTO collection_item_versions (item_id, collection_id, site_id, html_content, template_id, position, created_by)
VALUES (sqlc.arg(item_id), sqlc.arg(collection_id), sqlc.arg(site_id), sqlc.arg(html_content), sqlc.arg(template_id), sqlc.arg(position), sqlc.arg(created_by));

-- name: GetCollectionItemVersionHistory :many
SELECT version_id, item_id, collection_id, site_id, html_content, template_id, position, created_at, created_by
FROM collection_item_versions
WHERE item_id = sqlc.arg(item_id) AND collection_id = sqlc.arg(collection_id) AND site_id = sqlc.arg(site_id)
ORDER BY created_at DESC
LIMIT sqlc.arg(limit_count);

-- name: GetCollectionItemVersion :one
SELECT version_id, item_id, collection_id, site_id, html_content, template_id, position, created_at, created_by
FROM collection_item_versions
WHERE version_id = sqlc.arg(version_id);

-- name: GetAllCollectionItemVersionsForSite :many
SELECT 
    civ.version_id, civ.item_id, civ.collection_id, civ.site_id, civ.html_content, civ.template_id, civ.position, civ.created_at, civ.created_by,
    ci.html_content as current_html_content, ci.position as current_position
FROM collection_item_versions civ
LEFT JOIN collection_items ci ON civ.item_id = ci.item_id AND civ.collection_id = ci.collection_id AND civ.site_id = ci.site_id
WHERE civ.site_id = sqlc.arg(site_id)
ORDER BY civ.created_at DESC
LIMIT sqlc.arg(limit_count);

-- name: DeleteOldCollectionItemVersions :exec
DELETE FROM collection_item_versions 
WHERE created_at < sqlc.arg(created_before) AND site_id = sqlc.arg(site_id);