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

const ImportRequestSchema = z.union([z.string(), z.object({ providers: z.unknown() })]);

export const Route = createFileRoute("/api/providers/import")({
  server: {
    handlers: {
      POST: async ({ request }: { request: Request }) => {
        try {
          const rawBody = await request.text();
          let jsonContent: string;
          try {
            const parsedBody: unknown = JSON.parse(rawBody);
            jsonContent = typeof parsedBody === "string" ? parsedBody : JSON.stringify(parsedBody);
          } catch {
            jsonContent = rawBody;
          }

          if (!jsonContent || jsonContent.trim() === "") {
            return Response.json({ error: "No JSON content provided" }, { status: 400 });
          }

          const result = importProviders(jsonContent);

          return Response.json({
            success: result.imported > 0,
            imported: result.imported,
            errors: result.errors,
            message:
              result.imported > 0
                ? `Successfully imported ${result.imported} provider(s)`
                : result.errors.length > 0
                  ? `Import completed with ${result.errors.length} error(s)`
                  : "No providers imported",
          });
        } catch (err) {
          return Response.json(
            { error: `Failed to import: ${err instanceof Error ? err.message : String(err)}` },
            { status: 400 },
          );
        }
      },
    },
  },
});
