exports.createLesson = async (req, res, next) => {
try {
const {
classId,
sow,
grade,
specificTopic,
activityType,
additionalNotes,
} = req.body;
// ... [Validation logic skipped for brevity] ...
const user = await User.findById(req.user.id).select("+geminiApiKey");
const geminiApiKey = user.getGeminiApiKey();
const genAI = new GoogleGenerativeAI(geminiApiKey);
// --- Context & Prompt Building ---
let promptContext = `
You are a Malaysia Educator. Your task is to create a lesson plan tally to Scheme of Work (SoW), You may be creative, engaging 60-minute lesson plan for a ${grade} class for the subject: ${subject}.
`;
// 1. Material & SOW Logic
if (materialPart || materialContent) {
promptContext += `
IMPORTANT: Base your lesson plan primarily on the provided material (attached document or text context).
${materialContent ? `--- MATERIAL CONTEXT ---\n${materialContent}\n--- END MATERIAL CONTEXT ---` : ""}
You should still align it with the SoW topic if provided below, but prioritize the material content.
SOW/Curriculum Context (for alignment only):
${JSON.stringify(sow, null, 2)}
`;
}
// ... [Prompt parameters construction] ...
promptContext += `
The ONLY acceptable format for the 'activities' object is shown in this example (Adapt content for ${subject}):
{
"learningObjective": "By the end of the lesson, students will be able to...",
"successCriteria": [ "I can...", "I can..." ],
"activities": {
"preLesson": [ "Teacher introduces...", "Students..." ],
"duringLesson": [ "Activity 1...", "Activity 2..." ],
"postLesson": [ "Closure activity..." ]
}
}
`;
// Call Gemini AI
const model = genAI.getGenerativeModel({ model: "gemini-2.0-flash" });
const result = await model.generateContent([promptContext]);
const response = await result.response;
const text = response.text();
// Parse and Validate JSON
const generatedPlan = JSON.parse(text.replace(/\`\`\`json/g, "").replace(/\`\`\`/g, "").trim());
// Validation using Joi
const { error, value } = lessonPlanValidationSchema.validate(generatedPlan);
if (error) throw new Error(`AI response failed validation: ${error.details[0].message}`);
res.status(200).json({ success: true, data: value });
} catch (error) {
console.error("Lesson generation error:", error.message);
res.status(500).json({ success: false, message: error.message });
}
};