"use server";

import { prisma } from "@repo/db";
import { sendMailByTemplate } from "../../../helper/mail";
import bcrypt from "bcryptjs";

export const resetPassword = async (email: string) => {
	try {
		const user = await prisma.user.findFirst({
			where: {
				email,
			},
		});

		if (!user) {
			return { error: "Nutzer nicht gefunden" };
		}

		const array = new Uint8Array(8);
		crypto.getRandomValues(array);
		const password = Array.from(array, (byte) =>
			("0" + (byte % 36).toString(36)).slice(-1),
		).join("");
		const hashedPassword = await bcrypt.hash(password, 12);
		await prisma.user.update({
			where: {
				email,
			},
			data: {
				password: hashedPassword,
			},
		});

		await sendMailByTemplate(user.email, "password-change", {
			user: user,
			password: password,
		});
		return {};
	} catch (error) {
		if (error instanceof Error) {
			return { error: error.message };
		} else {
			return { error: "Ein Fehler ist aufgetreten" };
		}
	}
};
