-- name: InsertMessage :one
INSERT INTO messages (conversation_id, role, content, status)
VALUES ($1, $2, $3, $4)
RETURNING *;

-- name: GetMessage :one
SELECT * FROM messages WHERE id = $1;

-- name: ListMessagesByConversation :many
SELECT * FROM messages
WHERE conversation_id = $1
  AND ($2::bigint = 0 OR id < $2)
ORDER BY id DESC
LIMIT $3;

-- name: ListMessagesAscending :many
SELECT * FROM messages WHERE conversation_id = $1 ORDER BY id ASC;

-- name: UpdateMessageOK :exec
UPDATE messages
SET content = $2, thinking = $3,
    prompt_tokens = $4, completion_tokens = $5, thinking_tokens = $6,
    status = 'ok', updated_at = NOW()
WHERE id = $1;

-- name: UpdateMessageError :exec
UPDATE messages
SET status = 'error', error_message = $2, updated_at = NOW()
WHERE id = $1;

-- name: UpdateMessageCancelled :exec
UPDATE messages
SET status = 'cancelled', updated_at = NOW()
WHERE id = $1;

-- name: DeleteMessage :exec
DELETE FROM messages WHERE id = $1;

-- name: GetFirstUserMessage :one
SELECT * FROM messages
WHERE conversation_id = $1 AND role = 'user'
ORDER BY id ASC LIMIT 1;

-- name: MarkPendingAsErrorOnStartup :exec
UPDATE messages
SET status = 'error', error_message = 'server restart', updated_at = NOW()
WHERE status = 'pending';
