"use server";
import { prisma, Prisma } from "@repo/db";
import bcrypt from "bcryptjs";

export const register = async ({
	password,
	...user
}: Omit<Prisma.UserCreateInput, "publicId">) => {
	const hashedPassword = await bcrypt.hash(password, 12);
	const lastUserPublicId = await prisma.user.findFirst({
		select: {
			publicId: true,
		},
		orderBy: {
			publicId: "desc",
		},
	});
	let varPublicId = "VAR0000";
	if (lastUserPublicId) {
		const lastUserInt = parseInt(lastUserPublicId.publicId.replace("VAR", ""));
		varPublicId = `VAR${(lastUserInt + 1).toString().padStart(4, "0")}`;
	}

	const newUser = prisma.user.create({
		data: {
			...user,
			publicId: varPublicId,
			password: hashedPassword,
		},
	});
	return newUser;
};
