-- name: ListImageReferences :many
SELECT r.id, r.tenant_id, r.image_asset_id, r.article_id, r.ref_scope, r.created_at
FROM image_asset_references r
WHERE r.tenant_id = sqlc.arg(tenant_id) AND r.image_asset_id = sqlc.arg(image_asset_id);

-- name: CountImageReferences :one
SELECT COUNT(*)::INT AS total
FROM image_asset_references
WHERE tenant_id = sqlc.arg(tenant_id) AND image_asset_id = sqlc.arg(image_asset_id);

-- name: UpsertImageReference :exec
INSERT INTO image_asset_references (tenant_id, image_asset_id, article_id, ref_scope)
VALUES (sqlc.arg(tenant_id), sqlc.arg(image_asset_id), sqlc.arg(article_id), sqlc.arg(ref_scope))
ON CONFLICT (image_asset_id, article_id, ref_scope) DO UPDATE SET updated_at = NOW();

-- name: DeleteImageReferencesByArticle :exec
DELETE FROM image_asset_references
WHERE tenant_id = sqlc.arg(tenant_id) AND article_id = sqlc.arg(article_id);

-- name: DeleteImageReferencesByArticleScope :exec
DELETE FROM image_asset_references
WHERE tenant_id = sqlc.arg(tenant_id) AND article_id = sqlc.arg(article_id) AND ref_scope = sqlc.arg(ref_scope);

-- name: ListImageReferenceArticles :many
SELECT DISTINCT r.article_id, r.ref_scope
FROM image_asset_references r
WHERE r.tenant_id = sqlc.arg(tenant_id) AND r.image_asset_id = sqlc.arg(image_asset_id);
