"use server";

import { prisma } from "@repo/db";
import { sendMailByTemplate } from "../../../helper/mail";
import OLD_USER from "../../api/auth/[...nextauth]/var.User.json";
import bcrypt from "bcryptjs";
import { createNewUserFromOld, OldUser } from "../../../types/oldUser";

export const resetPassword = async (email: string) => {
	try {
		let user = await prisma.user.findFirst({
			where: {
				email,
			},
		});
		const oldUser = (OLD_USER as OldUser[]).find((u) => u.email === email);
		if (!user) {
			if (oldUser) {
				user = await createNewUserFromOld(oldUser);
				// If the user is not found in the new database, check the old user data
			} else {
				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" };
		}
	}
};
