'use strict';

// Shared "all sessions" read query. Extracted from db.getAllSessionsData() so the
// SAME logic runs both on the main thread (db.js, via the live connection) AND on the
// read-pool worker (via a read-only connection) — keeping the recent-sessions rebuild
// off the main event loop (opportunity A follow-up). It is a pure read (two window-
// function queries + an in-memory join), so it is safe to run on a read-only WAL
// connection in a worker. Takes the database handle as a parameter — no module-level
// connection — so neither caller can accidentally diverge from the other.

function _columnSet(d, table) {
  try {
    return new Set(d.prepare(`PRAGMA table_info(${table})`).all().map(c => c.name));
  } catch {
    return new Set();
  }
}

function queryAllSessionsData(d) {
  const scCols = _columnSet(d, 'session_conversations');
  const scLastMessageAt = scCols.has('last_message_at') ? 'sc.last_message_at' : "''";
  const rows = d.prepare(`
    SELECT c.*, a.agent_session_id, a.provider_resume_id, a.jsonl_path, a.first_message, a.file_size,
      a.modified_at, a.hostname, a.model, a.git_branch,
      a.thread_source, a.parent_agent_session_id, a.agent_nickname, a.agent_role,
      COALESCE(agent_list.agent_session_ids, '') as agent_session_ids,
      COALESCE(agent_list.agent_session_count, 0) as agent_session_count,
      MAX(COALESCE(a.user_msg_count, 0), COALESCE(sc.user_msg_count, 0)) as user_msg_count,
      COALESCE(NULLIF(a.last_user_content, ''), sc.last_user_content) as last_user_content,
      COALESCE(NULLIF(a.first_assistant_text, ''), sc.first_assistant_text) as first_assistant_text,
      COALESCE(NULLIF(a.rename_name, ''), sc.rename_name) as rename_name,
      COALESCE(NULLIF(${scLastMessageAt}, ''), '') as last_message_at
    FROM ctm_sessions c
    LEFT JOIN (
      SELECT *, ROW_NUMBER() OVER (
        PARTITION BY ctm_session_id
        ORDER BY COALESCE(NULLIF(modified_at, ''), updated_at, created_at) DESC,
          updated_at DESC,
          created_at DESC
      ) as rn
      FROM agent_sessions
    ) a ON a.ctm_session_id = c.id AND a.rn = 1
    LEFT JOIN (
      SELECT ctm_session_id,
        group_concat(agent_session_id, ',') as agent_session_ids,
        COUNT(*) as agent_session_count
      FROM (
        SELECT ctm_session_id, agent_session_id
        FROM agent_sessions
        ORDER BY COALESCE(NULLIF(modified_at, ''), updated_at, created_at) DESC,
          updated_at DESC,
          created_at DESC
      ) ordered_agents
      GROUP BY ctm_session_id
    ) agent_list ON agent_list.ctm_session_id = c.id
    LEFT JOIN session_conversations sc ON sc.ctm_session_id = a.agent_session_id
  `).all();

  const agentRows = d.prepare(`
    SELECT
      a.agent_session_id,
      a.ctm_session_id,
      a.provider,
      a.provider_resume_id,
      a.project_path,
      a.jsonl_path,
      COALESCE(NULLIF(a.first_message, ''), sc.first_message) as first_message,
      a.file_size,
      a.modified_at,
      a.hostname,
      COALESCE(NULLIF(a.model, ''), sc.model_id) as model,
      sc.model_provider as model_provider,
      COALESCE(NULLIF(a.git_branch, ''), sc.git_branch) as git_branch,
      MAX(COALESCE(a.user_msg_count, 0), COALESCE(sc.user_msg_count, 0)) as user_msg_count,
      a.slug,
      a.thread_source,
      a.parent_agent_session_id,
      a.agent_nickname,
      a.agent_role,
      a.created_at,
      a.updated_at,
      COALESCE(NULLIF(a.last_user_content, ''), sc.last_user_content) as last_user_content,
      COALESCE(NULLIF(a.first_assistant_text, ''), sc.first_assistant_text) as first_assistant_text,
      COALESCE(NULLIF(a.rename_name, ''), sc.rename_name) as rename_name,
      COALESCE(NULLIF(${scLastMessageAt}, ''), '') as last_message_at
    FROM agent_sessions a
    LEFT JOIN session_conversations sc ON sc.ctm_session_id = a.agent_session_id
    ORDER BY
      a.ctm_session_id ASC,
      COALESCE(NULLIF(a.modified_at, ''), a.updated_at, a.created_at) DESC,
      a.created_at DESC
  `).all();

  const byCtmId = new Map();
  for (const agent of agentRows) {
    if (!agent.ctm_session_id) continue;
    if (!byCtmId.has(agent.ctm_session_id)) byCtmId.set(agent.ctm_session_id, []);
    byCtmId.get(agent.ctm_session_id).push(agent);
  }

  for (const row of rows) {
    row.agent_sessions = byCtmId.get(row.id) || [];
    row.agent_session_count = row.agent_sessions.length;
  }
  return rows;
}

module.exports = { queryAllSessionsData };
