import { createFileRoute } from "@tanstack/react-router";
import { z } from "zod";
import { getProviders, addProvider } from "../../proxy/providers";

const ProviderInputSchema = z.object({
  name: z.string().min(1, "Name is required"),
  apiKey: z.string().min(1, "API key is required"),
  format: z.enum(["anthropic", "openai"]).optional(),
  anthropicBaseUrl: z.string().optional(),
  openaiBaseUrl: z.string().optional(),
  models: z.array(z.string()).min(1, "At least one model is required"),
  model: z.string().optional(),
  authHeader: z.enum(["bearer", "x-api-key"]).optional().default("bearer"),
  apiDocsUrl: z.string().optional(),
  source: z.enum(["company", "personal"]).optional(),
});

export const Route = createFileRoute("/api/providers")({
  server: {
    handlers: {
      GET: () => {
        return Response.json(getProviders());
      },
      POST: async ({ request }: { request: Request }) => {
        const parsed = ProviderInputSchema.safeParse(await request.json());
        if (!parsed.success) {
          return Response.json({ error: parsed.error.message }, { status: 400 });
        }
        const newProvider = addProvider(
          parsed.data.name,
          parsed.data.apiKey,
          parsed.data.format,
          undefined, // baseUrl (legacy) — use format-specific URLs instead
          parsed.data.models,
          parsed.data.authHeader,
          parsed.data.apiDocsUrl,
          parsed.data.anthropicBaseUrl,
          parsed.data.openaiBaseUrl,
          parsed.data.source,
        );
        return Response.json(newProvider, { status: 201 });
      },
    },
  },
});
