-- name: SelectCharacterByID :one
SELECT * FROM data_character WHERE id = sqlc.arg(id)::text;

-- name: SelectCharacterByNick :one
SELECT * FROM data_character WHERE nicks <@ ARRAY[sqlc.arg(nick)::text];

-- name: SelectCharacterByName :one
SELECT * FROM data_character WHERE name = sqlc.arg(name)::text;

-- name: SelectCharacters :many
SELECT * FROM data_character
WHERE (sqlc.arg(filter_id)::bool = false OR id = ANY(sqlc.arg(ids)::text[]))
    AND (sqlc.arg(filter_name)::bool = false OR name = ANY(sqlc.arg(names)::text[]))
    AND (sqlc.arg(filter_nick)::bool = false OR nicks && (sqlc.arg(nicks)::text[]))
    AND (sqlc.arg(filter_author)::bool = false OR author = sqlc.arg(author)::text)
    AND (sqlc.arg(filter_search)::bool = false OR "ts_vector" @@ to_tsquery(sqlc.arg(search)::text))
LIMIT sqlc.arg(limit_size)::int;

-- name: InsertCharacter :exec
INSERT INTO data_character (id, nicks, name, short_name, author, description, ts_vector) VALUES (
    sqlc.arg(id)::text, sqlc.arg(nicks)::text[], sqlc.arg(name)::text,
    sqlc.arg(short_name)::text, sqlc.arg(author)::text, sqlc.arg(description)::text,
    to_tsvector(
        'english',
        sqlc.arg(name)::text || ' ' || sqlc.arg(description)::text || ' ' || sqlc.arg(author)::text || ' '
                             || immutable_array_to_string(
            sqlc.arg(nicks)::text[], ' '
        )
    )
);

-- name: UpdateCharacter :exec
UPDATE data_character
SET name=sqlc.arg(name)::text,
    short_name=sqlc.arg(short_name)::text,
    description=sqlc.arg(description)::text
WHERE id=sqlc.arg(id)::text;

-- name: AddCharacterNick :exec
UPDATE data_character
SET nicks=append(nicks, sqlc.arg(nick)::text)
WHERE id=sqlc.arg(id)::text;

-- name: RemoveCharacterNick :exec
UPDATE data_character
SET nicks=array_remove(nicks, sqlc.arg(nick)::text)
WHERE id=sqlc.arg(id)::text;

-- name: DeleteCharacter :exec
DELETE FROM data_character WHERE id=$1;