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

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

export const Route = createFileRoute("/api/providers/$providerId")({
  server: {
    handlers: {
      GET: ({ params }: { params: { providerId: string } }) => {
        const providers = getProviders();
        const provider = providers.find((p) => p.id === params.providerId);
        if (!provider) {
          return Response.json({ error: "Provider not found" }, { status: 404 });
        }
        return Response.json(provider);
      },
      PUT: async ({ params, request }: { params: { providerId: string }; request: Request }) => {
        const parsed = ProviderUpdateSchema.safeParse(await request.json());
        if (!parsed.success) {
          return Response.json({ error: parsed.error.message }, { status: 400 });
        }
        const updated = updateProvider(params.providerId, parsed.data);
        if (!updated) {
          return Response.json({ error: "Provider not found" }, { status: 404 });
        }
        return Response.json(updated);
      },
      DELETE: ({ params }: { params: { providerId: string } }) => {
        const deleted = deleteProvider(params.providerId);
        if (!deleted) {
          return Response.json({ error: "Provider not found" }, { status: 404 });
        }
        return Response.json({ success: true });
      },
    },
  },
});
