-- name: SetTag :exec
INSERT INTO common_tag (tag, target_kind, target_id)
VALUES (
    @tag::TEXT, @target_kind::TEXT, @target_id::TEXT
)
ON CONFLICT DO NOTHING;

-- name: SetTags :exec
INSERT INTO common_tag (tag, target_kind, target_id)
SELECT unnest(@tags::TEXT[]), @target_kind::TEXT as target_kind, @target_id::TEXT as target_id
ON CONFLICT DO NOTHING;

-- name: ClearTag :exec
DELETE FROM common_tag
WHERE tag = @tag::TEXT
  AND target_kind = @target_kind::TEXT
  AND target_id = @target_id::TEXT;

-- name: ClearTagsByTargetLike :exec
DELETE FROM common_tag
WHERE target_kind = @target_kind::TEXT
  AND target_id = @target_id::TEXT
  AND tag LIKE @tag_like::TEXT;

-- name: ClearTagsByTarget :exec
DELETE FROM common_tag
WHERE target_kind = @target_kind::TEXT
  AND target_id = @target_id::TEXT;

-- name: SetCharacterTagsFromIDs :exec
INSERT INTO common_tag
SELECT 'Character:'||name AS tag, @target_kind::TEXT as target_kind, @target_id::TEXT as target_id
FROM data_character WHERE id = ANY(@character_ids::TEXT[])
ON CONFLICT DO NOTHING;

-- name: SetLocationTagFromChannelName :exec
INSERT INTO common_tag
SELECT 'Location:'||location_name AS tag, @target_kind::TEXT as target_kind, @target_id::TEXT as target_id
FROM data_channel
WHERE name = @channel_name AND location_name != ''
ON CONFLICT DO NOTHING;

-- name: SelectDistinctTags :many
SELECT DISTINCT tag FROM common_tag ORDER BY tag;

-- name: SelectDistinctTagsLike :many
SELECT DISTINCT tag FROM common_tag WHERE tag LIKE $1::text ORDER BY tag;

-- name: SelectTagsByTag :many
SELECT * FROM common_tag WHERE tag = @tag_name::text ORDER BY tag;

-- name: SelectTagsByTags :many
SELECT * FROM common_tag WHERE tag = ANY(@tag_names::text[]) ORDER BY tag;

-- name: SelectTargetsByTags :many
SELECT DISTINCT target_id FROM common_tag WHERE tag = ANY(@tag_names::text[]) AND target_kind = @target_kind::text;

-- name: SelectTagsByTarget :many
SELECT * FROM common_tag WHERE target_kind = @target_kind AND target_id = @target_id::text ORDER BY tag;

-- name: SelectTagsByTargets :many
SELECT * FROM common_tag WHERE target_kind = @target_kind AND target_id = ANY(@target_ids::text[]) ORDER BY tag;
