import { parse } from "csv-parse/sync"; import fs from "fs/promises"; import { NextResponse } from "next/server"; import path from "path"; import { PrismaClient } from "@prismaclient"; // Path to CSV file const csvFilePath = path.resolve(process.cwd(), "public/scientists.csv"); const prisma = new PrismaClient(); type CsvRow = { Name: string; Level?: string; UserId: string; SuperiorId?: string; }; function normalizeLevel(level: string | undefined): string { // Only allow JUNIOR, SENIOR; default JUNIOR if (!level || !level.trim()) return "JUNIOR"; const lv = level.trim().toUpperCase(); return ["JUNIOR", "SENIOR"].includes(lv) ? lv : "JUNIOR"; } export async function POST() { try { // 1. Read the CSV file const fileContent = await fs.readFile(csvFilePath, "utf8"); // 2. Parse the CSV const records: CsvRow[] = parse(fileContent, { columns: true, skip_empty_lines: true, }); // 3. Transform each record for Prisma const scientists = records.map((row) => ({ name: row.Name, level: normalizeLevel(row.Level), userId: parseInt(row.UserId, 10), superiorId: row.SuperiorId && row.SuperiorId.trim() !== "" ? parseInt(row.SuperiorId, 10) : null, })); // 4. Bulk create scientists in database await prisma.scientist.createMany({ data: scientists, skipDuplicates: true, // in case the scientist/userid combo already exists }); return NextResponse.json({ success: true, count: scientists.length }); } catch (error: any) { console.error(error); return NextResponse.json({ success: false, error: error.message }, { status: 500 }); } finally { await prisma.$disconnect(); } }