import { db } from "../db/db.controller.js";
import { returnFunc } from "./returnHelper.utils.js";

export function generateSixDigitPin() {
	return Math.floor(100000 + Math.random() * 900000).toString();
}

export async function generateUniquePin() {
	for (let i = 0; i < 10; i++) {
		const pin = generateSixDigitPin();

		const existing = await db.query.scanUser.findFirst({
			where: (u, { eq }) => eq(u.pinHash, pin),
		});

		if (!existing)
			return returnFunc({
				success: true,
				level: "info",
				module: "utils",
				subModule: "genPin",
				message: "New pin generated",
				data: [{ pin: pin }],
				notify: false,
				room: "",
			});
	}

	return returnFunc({
		success: false,
		level: "error",
		module: "utils",
		subModule: "genPin",
		message: "Failed to generate unique PIN after 10 attempts",
		data: [],
		notify: true,
		room: "",
	});
}

// export const pinExists = async (pin: string | number) => {
// 	const existing = await db.query.scanUser.findFirst({
// 		where: (u, { eq }) => eq(u.pinHash, pin),
// 	});

// 	if (!existing) return true;

// 	return false;
// };
