import { createFileRoute } from "@tanstack/react-router";
import { z } from "zod";
import { clearAllLogs, clearLogsByIds, getFilteredLogs } from "../../proxy/store";

const DeleteBodySchema = z
  .object({
    ids: z.array(z.number().int().positive()).optional(),
  })
  .optional();

export const Route = createFileRoute("/api/logs")({
  server: {
    handlers: {
      GET: ({ request }: { request: Request }) => {
        const url = new URL(request.url);
        const sessionId = url.searchParams.get("sessionId") ?? undefined;
        const model = url.searchParams.get("model") ?? undefined;
        const offset = Number(url.searchParams.get("offset") ?? 0);
        const limit = Number(url.searchParams.get("limit") ?? 50);

        const allLogs = getFilteredLogs(sessionId, model);
        const paginatedLogs = allLogs.slice(offset, offset + limit);

        return Response.json({
          logs: paginatedLogs,
          total: allLogs.length,
          offset,
          limit,
        });
      },
      DELETE: async ({ request }: { request: Request }) => {
        let body: z.infer<typeof DeleteBodySchema> = undefined;
        try {
          const raw = await request.text();
          if (raw !== "") {
            const parsed: unknown = JSON.parse(raw);
            const result = DeleteBodySchema.safeParse(parsed);
            if (!result.success) {
              return Response.json(
                { error: "Invalid request body", details: result.error.format() },
                { status: 400 },
              );
            }
            body = result.data;
          }
        } catch {
          return Response.json({ error: "Invalid JSON body" }, { status: 400 });
        }

        if (body?.ids !== undefined && body.ids.length > 0) {
          const result = clearLogsByIds(body.ids);
          return Response.json({ success: true, cleared: result.cleared });
        }
        const result = clearAllLogs();
        return Response.json({ success: true, cleared: result.cleared });
      },
    },
  },
});
