import { PrismaClient } from '@prisma/client';
import { writeFile } from 'fs/promises';
import { randomUUID } from 'crypto';
import { json } from '@sveltejs/kit';

const prisma = new PrismaClient();

export async function POST({ request }: RequestEvent) {
	const formData = await request.formData();

	const get = (key: string) => formData.get(key)?.toString() ?? '';

	// const pdfs = formData.getAll('pdfs') as File[];
	const pdfFiles = formData.getAll('pdfs') as File[];
	const hasValidPdf = pdfFiles.some((file) => file.size > 0 && file.type === 'application/pdf');
	if (!hasValidPdf) {
		return json({ error: 'Bitte lade das Zeugnis hoch in PDF Format.' }, { status: 400 });
	}
	const pdfData = [];

	// const gespeichertePfade: string[] = [];
	const noteDeutsch = Number(get('noteDeutsch'));
	const noteMathe = Number(get('noteMathe'));

	if (isNaN(noteDeutsch) || isNaN(noteMathe)) {
		return json({ error: 'Bitte gib gültige Noten an.' }, { status: 400 });
	}

	for (const file of pdfFiles) {
		if (file.size > 0 && file.type === 'application/pdf') {
			const buffer = Buffer.from(await file.arrayBuffer());
			const filename = `${randomUUID()}.pdf`;
			const uploadPath = `/uploads/${filename}`;
			await writeFile(`static${uploadPath}`, buffer);
			pdfData.push({ pfad: uploadPath });
		}
	}

	try {
		const anmeldung = await prisma.anmeldung.create({
			data: {
				// Persönliche Daten
				anrede: formData.get('anrede') as string,
				vorname: formData.get('vorname') as string,
				nachname: formData.get('nachname') as string,
				geburtsdatum: formData.get('geburtsdatum') as string,
				// Adresse
				strasse: formData.get('strasse') as string,
				hausnummer: formData.get('hausnummer') as string,
				ort: formData.get('ort') as string,
				plz: formData.get('plz') as string,
				// Kontakt
				telefon: formData.get('telefon') as string,
				email: formData.get('email') as string,
				// Schule
				schulart: formData.get('schulart') as string,
				schulklasse: formData.get('schulklasse') as string,
				noteDeutsch: parseInt(formData.get('noteDeutsch') as string),
				noteMathe: parseInt(formData.get('noteMathe') as string),
				sozialverhalten: (formData.get('sozialverhalten') as string) || null,
				// Praktikum
				praktikumId: parseInt(formData.get('zeitraum') as string),
				motivation: (formData.get('motivation') as string) || '',
				// Wünsche
				wunsch1Id: parseInt(formData.get('wunsch1Id') as string),
				wunsch2Id: parseInt(formData.get('wunsch2Id') as string),
				wunsch3Id: parseInt(formData.get('wunsch3Id') as string),
				// Alter (falls vom Frontend gesendet)
				alter: formData.get('alter') ? parseInt(formData.get('alter') as string) : null,
				// Notfallkontakt
				notfallVorname: (formData.get('notfallVorname') as string) || null,
				notfallNachname: (formData.get('notfallNachname') as string) || null,
				notfallTelefon: (formData.get('notfallTelefon') as string) || null,
				// System
				zugewiesenId: null,
				// timestamp wird automatisch durch @default(now()) gesetzt
				pdfs: {
					create: pdfData
				}
			}
		});

		return json({ success: true, anmeldung });
	} catch (err: unknown) {
		if (err instanceof Error && (err as { code?: string }).code === 'P2002') {
			return json({ error: 'Diese E-Mail wurde bereits verwendet.' }, { status: 400 });
		}

		console.error(err);
		return json({ error: 'Fehler beim Speichern.' }, { status: 500 });
	}
}
