import { createFileRoute } from "@tanstack/react-router";
import { z } from "zod";
import { MAX_SLOW_RESPONSE_THRESHOLD_SECONDS } from "../../lib/runtimeConfig";
import { getConfig, setConfig, RuntimeConfigSchema } from "../../proxy/config";

// Partial schema for PATCH: at least one known field must be present.
const RuntimeConfigPatchSchema = z
  .object({
    stripClaudeCodeBillingHeader: z.boolean().optional(),
    hasSeenOnboarding: z.boolean().optional(),
    slowResponseThresholdSeconds: z
      .number()
      .int()
      .min(0)
      .max(MAX_SLOW_RESPONSE_THRESHOLD_SECONDS)
      .optional(),
  })
  .strict()
  .refine((v) => Object.keys(v).length > 0, {
    message: "At least one field must be provided",
  });

export const Route = createFileRoute("/api/config")({
  server: {
    handlers: {
      GET: () => {
        return Response.json(getConfig());
      },
      PATCH: async ({ request }: { request: Request }) => {
        let body: unknown;
        try {
          body = await request.json();
        } catch {
          return Response.json({ error: "Invalid JSON body" }, { status: 400 });
        }

        const result = RuntimeConfigPatchSchema.safeParse(body);
        if (!result.success) {
          return Response.json(
            {
              error: "Invalid config payload",
              issues: result.error.issues,
            },
            { status: 400 },
          );
        }

        const updated = setConfig(result.data);
        return Response.json(updated satisfies z.infer<typeof RuntimeConfigSchema>);
      },
    },
  },
});
