import userFile from "./users.json" assert { type: "json" };
import newUserIdMap from "./new-user-id-map.json" assert { type: "json" };
import { Enums, prisma } from "#lib/server/prisma";
import * as fs from "fs";
import { fileURLToPath } from "url";

const users = userFile[2].data;

const saveUserMap = () => {
	fs.writeFileSync(
		fileURLToPath(new URL("./new-user-id-map.json", import.meta.url)),
		JSON.stringify(newUserIdMap)
	);
};

if (!users) {
	throw new Error("Invalid dataset");
}

let i = 0;
for (const user of users) {
	if (user.id in newUserIdMap) {
		continue;
	}

	try {
		const benutzer = await prisma.benutzer.create({
			data: {
				email: user.email,
				passwort: user.password,
				adresse: user.adresse,
				anrede: user.anrede,
				name: user.name,
				vorname: user.vorname,
				ort: user.ort,
				plz: user.plz,
				rolle:
					parseInt(user.level) == 4
						? Enums.BenutzerRolle.ADMIN
						: Enums.BenutzerRolle.USER,
				firma: user.firma,
				lex_office_id: user.lex_office_id,
				telefon: user.phone,
			},
			select: {
				uid: true,
			},
		});

		newUserIdMap[user.id] = benutzer.uid;
	} catch (e) {
		saveUserMap();
		throw e;
	}

	// Alle 50 werden gespeichert.
	if (i % 50 == 0) {
		saveUserMap();
	}

	i++;
}