-- Collection templates table queries

-- name: GetCollectionTemplate :one
SELECT template_id, collection_id, site_id, name, html_template, is_default, created_at
FROM collection_templates 
WHERE template_id = sqlc.arg(template_id);

-- name: GetCollectionTemplates :many
SELECT template_id, collection_id, site_id, name, html_template, is_default, created_at
FROM collection_templates 
WHERE collection_id = sqlc.arg(collection_id) AND site_id = sqlc.arg(site_id)
ORDER BY is_default DESC, created_at ASC;

-- name: GetDefaultTemplate :one
SELECT template_id, collection_id, site_id, name, html_template, is_default, created_at
FROM collection_templates 
WHERE collection_id = sqlc.arg(collection_id) AND site_id = sqlc.arg(site_id) AND is_default = TRUE
LIMIT 1;

-- name: CreateCollectionTemplate :one
INSERT INTO collection_templates (collection_id, site_id, name, html_template, is_default)
VALUES (sqlc.arg(collection_id), sqlc.arg(site_id), sqlc.arg(name), sqlc.arg(html_template), sqlc.arg(is_default))
RETURNING template_id, collection_id, site_id, name, html_template, is_default, created_at;

-- name: UpdateCollectionTemplate :one
UPDATE collection_templates 
SET name = sqlc.arg(name), html_template = sqlc.arg(html_template), is_default = sqlc.arg(is_default)
WHERE template_id = sqlc.arg(template_id)
RETURNING template_id, collection_id, site_id, name, html_template, is_default, created_at;

-- name: SetTemplateAsDefault :exec
UPDATE collection_templates 
SET is_default = CASE 
    WHEN template_id = sqlc.arg(template_id) THEN TRUE
    ELSE FALSE
END
WHERE collection_id = sqlc.arg(collection_id) AND site_id = sqlc.arg(site_id);

-- name: DeleteCollectionTemplate :exec
DELETE FROM collection_templates 
WHERE template_id = sqlc.arg(template_id);

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