-- name: SelectPost :one
SELECT id, log_short_id, time, kind, nick, text, position FROM log_post WHERE id=$1 LIMIT 1;

-- name: SelectLogIDsFromPostSearch :many
SELECT DISTINCT(log_short_id) FROM log_post WHERE "ts_vector" @@ to_tsquery(@search::TEXT);

-- name: SelectPostsByPositionRange :many
SELECT id, log_short_id, time, kind, nick, text, position FROM log_post WHERE log_short_id = @log_short_id AND position >= @from_position AND position <= @to_position;

-- name: SelectPositionsByLogShortID :many
SELECT position FROM log_post WHERE log_short_id = $1 ORDER BY position;

-- name: SelectPosts :many
SELECT id, log_short_id, time, kind, nick, text, position FROM log_post
WHERE (@filter_ids::BOOL = false OR id = ANY(@ids::TEXT[]))
  AND (@filter_kinds::BOOL = false OR kind = ANY(@kinds::TEXT[]))
  AND (@filter_log_short_id::BOOL = false OR log_short_id = @log_short_id)
  AND (@filter_search::BOOL = false OR "ts_vector" @@ to_tsquery(@search::TEXT))
ORDER BY log_short_id, position
LIMIT NULLIF(@limit_size::INT, 0);

-- name: InsertPost :one
INSERT INTO log_post (id, log_short_id, time, kind, nick, text, position, ts_vector)
    SELECT @id, @log_short_id, @time, @kind, @nick, @text, COALESCE(MAX(position), 0)+1, to_tsvector(@nick || ' ' || @text)
    FROM log_post
    WHERE log_short_id = @log_short_id
RETURNING position;

-- name: InsertPosts :one
INSERT INTO log_post (id, log_short_id, time, kind, nick, text, position, ts_vector)
    SELECT UNNEST(@ids::TEXT[]), @log_short_id, UNNEST(@times::TIMESTAMP[]), UNNEST(@kinds::TEXT[]),
           UNNEST(@nicks::TEXT[]), UNNEST(@texts::TEXT[]), COALESCE(MAX(position), 0) + UNNEST(@offsets::INT[]),
           to_tsvector(UNNEST(@nicks::TEXT[]) || ' ' || UNNEST(@texts::TEXT[]))
    FROM log_post
    WHERE log_short_id = @log_short_id
RETURNING position;

-- name: UpdatePost :exec
UPDATE log_post
SET time = @time,
    kind = @kind,
    nick = @nick,
    text = @text,
    ts_vector = to_tsvector(@nick || ' ' || @text)
WHERE id = @id;

-- name: MovePost :exec
UPDATE log_post SET position = @position WHERE id = @id;

-- name: ShiftPostsBetween :exec
UPDATE log_post SET position = position + @shift_offset::INT WHERE log_short_id = @log_short_id AND position >= @from_position AND position <= @to_position;

-- name: ShiftPostsAfter :exec
UPDATE log_post SET position = position + @shift_offset::INT WHERE log_short_id = @log_short_id AND position >= @from_position;

-- name: ShiftPostsBefore :exec
UPDATE log_post SET position = position + @shift_offset::INT WHERE log_short_id = @log_short_id AND position <= @to_position;

-- name: DeletePost :exec
DELETE FROM log_post WHERE id = @id;

-- name: DeletePostsByLogShortID :exec
DELETE FROM log_post WHERE log_short_id = @log_short_id;