import { UUidWithPrefix } from "#components/Ausweis/types.js";
import { hashPassword } from "#lib/password.js";
import { prisma } from "#lib/server/prisma";
import { APIError, defineApiRoute } from "astro-typesafe-api/server";
import { z } from "zod";

export const PUT = defineApiRoute({
	input: z.object({
		email: z.string().email(),
		passwort: z.string().min(8),
		vorname: z.string(),
		name: z.string()
	}),
	output: z.object({
		uid: UUidWithPrefix
	}),
	async fetch(input) {
		const user = await prisma.benutzer.findUnique({
			where: {
				email: input.email
			}
		})

		if (user) {
			throw new APIError({
				code: "CONFLICT",
				message: "Email Adresse ist bereits vergeben."
			})
		}

		const { uid } = await prisma.benutzer.create({
			data: {
				email: input.email,
				passwort: hashPassword(input.passwort),
				vorname: input.vorname,
				name: input.name
			}
		})

		return { uid }
	},
})