import { unstable_cache } from "next/cache"
import { prisma } from "@/lib/prisma"

export const getTraceData = unstable_cache(
  async (tracePrefix: string) => {
    const [rawLlmCalls, errors, optimizationFeatures, optimizationEvent] = await Promise.all([
      prisma.llm_calls.findMany({
        where: { trace_id: { startsWith: tracePrefix } },
        orderBy: { created_at: "asc" },
        select: {
          id: true,
          trace_id: true,
          call_type: true,
          model_name: true,
          status: true,
          latency_ms: true,
          llm_cost: true,
          total_tokens: true,
          created_at: true,
          context: true,
        },
      }),
      prisma.optimization_errors.findMany({
        where: { trace_id: { startsWith: tracePrefix } },
        orderBy: { created_at: "asc" },
      }),
      prisma.optimization_features.findFirst({
        where: { trace_id: { startsWith: tracePrefix } },
      }),
      prisma.optimization_events.findFirst({
        where: { trace_id: { startsWith: tracePrefix } },
        select: { event_type: true, function_name: true, file_path: true },
      }),
    ])
    return { rawLlmCalls, errors, optimizationFeatures, optimizationEvent }
  },
  ["observability-trace-detail"],
  { revalidate: 60 },
)

export type TraceData = Awaited<ReturnType<typeof getTraceData>>
