import { createFileRoute } from "@tanstack/react-router";
import { getLogById } from "../../proxy/store";
import { readChunks } from "../../proxy/chunkStorage";

export const Route = createFileRoute("/api/logs/$id/chunks")({
  server: {
    handlers: {
      GET: async ({ params }: { params: { id: string } }) => {
        const id = Number(params.id);
        if (isNaN(id)) {
          return Response.json({ error: "Invalid log ID" }, { status: 400 });
        }

        const log = await getLogById(id);
        if (log === null) {
          return Response.json({ error: "Log not found" }, { status: 404 });
        }

        // Try disk file first (persistent chunks from real proxy streaming)
        if (log.streamingChunksPath !== null && log.streamingChunksPath !== undefined) {
          const chunksData = readChunks(log.streamingChunksPath);
          if (chunksData !== null) {
            return Response.json(chunksData);
          }
        }

        // Fall back to in-memory streamingChunks (e.g., from provider test)
        if (log.streamingChunks !== undefined && log.streamingChunks.chunks.length > 0) {
          return Response.json(log.streamingChunks);
        }

        return Response.json({ error: "Chunks not found" }, { status: 404 });
      },
    },
  },
});
