import { NextResponse } from "next/server"; import { PrismaClient } from "@prisma/client"; import fs from "fs/promises"; import path from "path"; import { parse } from "csv-parse/sync"; // Path to users.csv - adjust as needed const csvFilePath = path.resolve(process.cwd(), "public/users.csv"); const prisma = new PrismaClient(); type CsvRow = { Name: string; Email: string; PasswordHash: string; Role?: string; }; function normalizeRole(role: string | undefined): string { // Only allow ADMIN, SCIENTIST, GUEST; default GUEST if (!role || !role.trim()) return "GUEST"; const r = role.trim().toUpperCase(); return ["ADMIN", "SCIENTIST", "GUEST"].includes(r) ? r : "GUEST"; } 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 CSV row to User model format const users = records.map(row => ({ name: row.Name, email: row.Email, passwordHash: row.PasswordHash, role: normalizeRole(row.Role), })); // 4. Bulk create users in database await prisma.user.createMany({ data: users, skipDuplicates: true, // because email is unique }); return NextResponse.json({ success: true, count: users.length }); } catch (error: any) { console.error(error); return NextResponse.json({ success: false, error: error.message }, { status: 500 }); } finally { await prisma.$disconnect(); } }