'use strict';

// Shared query for /api/prompt-executions, used by BOTH the main-thread handler
// (api-prompts.js handleListExecutions) and the read-pool worker
// (read-pool-worker.js 'listPromptExecutions' op) so the two can never diverge —
// parity by construction. The .all() can return up to 10000 rows each carrying a
// large message_text, which a CPU profile showed blocking the main event loop
// ~3.9s on the request path; the worker runs the exact same SQL off-thread.
function queryPromptExecutions(conn, opts = {}) {
  const limit = Math.max(1, Math.min(parseInt(opts.limit, 10) || 50, 10000));
  const order = String(opts.order || 'desc').toLowerCase() === 'asc' ? 'ASC' : 'DESC';
  const role = opts.role || null;
  const project = opts.project || null;
  const after = opts.after || null;
  let sql = 'SELECT * FROM prompt_executions WHERE 1=1';
  const params = [];
  if (role) { sql += ' AND role = ?'; params.push(role); }
  if (project) { sql += ' AND project_path LIKE ?'; params.push('%' + project + '%'); }
  if (after) { sql += ' AND executed_at > ?'; params.push(after); }
  sql += ` ORDER BY executed_at ${order}, session_id ASC, message_index ASC LIMIT ?`;
  params.push(limit);
  return conn.prepare(sql).all(...params);
}

module.exports = { queryPromptExecutions };
