-- name: InsertConversation :one
INSERT INTO conversations (id, user_id, project_id, workspace_id, issue_id, model_id, system_prompt, title, requirement_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
RETURNING *;

-- name: GetConversation :one
SELECT * FROM conversations WHERE id = $1 AND deleted_at IS NULL;

-- name: ListConversationsByUser :many
SELECT * FROM conversations
WHERE user_id = $1 AND deleted_at IS NULL
  AND ($2::uuid IS NULL OR project_id = $2)
  AND ($3::uuid IS NULL OR workspace_id = $3)
  AND ($4::uuid IS NULL OR issue_id = $4)
  AND ($5::uuid IS NULL OR requirement_id = $5)
  AND ($6::text = '' OR title ILIKE '%' || $6 || '%')
ORDER BY updated_at DESC
LIMIT $7;

-- name: UpdateConversationTitle :exec
UPDATE conversations SET title = $2, title_generated_at = NOW(), updated_at = NOW()
WHERE id = $1;

-- name: SetConversationTitleManual :exec
UPDATE conversations SET title = $2, updated_at = NOW() WHERE id = $1;

-- name: SoftDeleteConversation :exec
UPDATE conversations SET deleted_at = NOW(), updated_at = NOW()
WHERE id = $1 AND deleted_at IS NULL;
