import {
  getDrizzle,
  init_drizzle
} from "./chunk-RII4M3J2.js";

// src/db/traces.ts
init_drizzle();
import { sql } from "drizzle-orm";
function listTraces(opts) {
  const db = getDrizzle();
  const { sessionId, limit } = opts;
  if (sessionId) {
    return db.all(sql`
      SELECT trace_id,
             MIN(received_at)           AS start_ms,
             MAX(received_at)           AS end_ms,
             COUNT(*)                   AS event_count,
             COUNT(DISTINCT session_id) AS session_count,
             MIN(session_id)            AS first_session_id
      FROM events
      WHERE trace_id IS NOT NULL AND session_id = ${sessionId}
      GROUP BY trace_id
      ORDER BY end_ms DESC
      LIMIT ${limit}
    `);
  }
  return db.all(sql`
    SELECT trace_id,
           MIN(received_at)           AS start_ms,
           MAX(received_at)           AS end_ms,
           COUNT(*)                   AS event_count,
           COUNT(DISTINCT session_id) AS session_count,
           MIN(session_id)            AS first_session_id
    FROM events
    WHERE trace_id IS NOT NULL
    GROUP BY trace_id
    ORDER BY end_ms DESC
    LIMIT ${limit}
  `);
}

export {
  listTraces
};
