const generateReferenceNumber = async (Model) => {
	let reference_no;
	let exists = true;

	const generateRandomPrefix = () => {
		const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		let prefix = '';
		for (let i = 0; i < 3; i++) {
			prefix += letters.charAt(Math.floor(Math.random() * letters.length));
		}
		return prefix;
	};

	while (exists) {
		const randomPrefix = generateRandomPrefix();
		const randomNumber = Math.floor(10000000 + Math.random() * 90000000);
		reference_no = `${randomPrefix}-${randomNumber}`;

		const existing = await Model.findOne({ where: { reference_no } });
		if (!existing) {
			exists = false;
		}
	}

	return reference_no;
};

module.exports = {
	generateReferenceNumber,
};
