import { apiHandler, db } from "@/helpers/api";

export default apiHandler({
	post: createCourse,
});

async function createCourse(req, res) {
	const userID = req.userID;
	const data = req.body.data;

	if (!db.initialized) await db.initialize();

	try {
		const userData = await db.User.findByPk(userID);

		if (!userData) return res.status(404).json({ error: "Unknown!" });

		if (userData.accountType == 0)
			return res.status(401).json({ error: "You are not authorized" });

		const insertedCourse = await db.Courses.create({
			instructorID: userData.id,
			instructorName: userData.userName,
			title: data.title,
			description: data.description,
			categoryName: data.categoryName,
			categoryURL: data.categoryURL,
			subcategoryName: data.subcategoryName,
			subcategoryURL: data.subcategoryURL,
               parentName: data.parentName, 
               parentURL: data.parentURL, 
			price: data.price,
			priceReduced: data.priceReduced,
			previewImage: data.previewImage,
			previewVideo: data.previewVideo,
			url: data.url,
               waiting: 1
		}); 

		const courseID = insertedCourse.id;
		const steps = data.steps;

	
		const moduleMap = {}; 

		for (const step of steps) {
			if (step.type === "module") {
				const insertedModule = await db.Modules.create({
					courseID: courseID,
					title: step.title,
					type: step.type,
					parentID: step.parentID,
				});
				moduleMap[step.id] = insertedModule.id;
			}
		}

		const chapterMap = {}; 

		for (const step of steps) {
			if (step.type === "chapter") {
				const insertedChapter = await db.Modules.create({
					courseID: courseID,
					title: step.title,
					type: 'chapter',
					parentID: moduleMap[step.parentID], 
				});
				chapterMap[step.id] = insertedChapter.id;
			}
		}

          let answerIndex = 0;

		for (const step of steps) {
			if (step.type === "lesson") {
				await db.Modules.create({
					courseID: courseID,
					title: step.title,
					type: 'lesson',
					parentID: chapterMap[step.parentID], 
					videoUrl: step.videoUrl,
                         duration: step.duration
				});
			}

               if (step.type === "question") {
                    const moduleId = moduleMap[step.parentID]; 

                    const answers = steps
                         .filter(answerStep => answerStep.type === "answer")
                         .slice(answerIndex, answerIndex + 3)  
                         .map(answerStep => ({
                              title: answerStep.title,
                              correct: answerStep.correctAnswer === 1 ? true : false, 
                         }));
            
                    answerIndex += 3;

                    await db.Modules.create({
                         courseID: courseID,
                         title: step.title,
                         type: "question",
                         parentID: moduleId, 
                         answers: JSON.stringify(answers), 
                    });
               }
		}

		return res.status(200).json({ courseURL: "/" + data.url });
	} catch (error) {
 
		return res.status(500).json({ error: error });
	}
}
