/**
 * ==================================================
 * Smart Attendance System
 * AI Controller
 * ==================================================
 * Handles AI-related requests.
 * ==================================================
 */

const AIService = require("./ai.service");
const EmbeddingService = require("../../services/embedding.service");

class AIController {

    /**
     * ==========================================
     * Train Student Face
     * ==========================================
     */

    static async train(req, res, next) {

        try {

            const { student_id } = req.body;

            if (!student_id) {

                return res.status(400).json({

                    success: false,

                    message: "Student ID is required."

                });

            }

            if (!req.files || req.files.length === 0) {

                return res.status(400).json({

                    success: false,

                    message: "Training images are required."

                });

            }

            //---------------------------------------
            // Image Paths
            //---------------------------------------

            const imagePaths = req.files.map(

                file => file.path

            );

            //---------------------------------------
            // Train using Python AI
            //---------------------------------------

            const aiResponse = await AIService.train(

                student_id,

                imagePaths

            );

            //---------------------------------------
            // Save Embedding
            //---------------------------------------

            await EmbeddingService.save({

                student_id: aiResponse.data.student_id,

                average_embedding:
                    aiResponse.data.average_embedding,

                trained_images:
                    aiResponse.data.embeddings_generated,

                embedding_dimension: 512,

                ai_model: "buffalo_l"

            });

            //---------------------------------------
            // Response
            //---------------------------------------

            return res.status(200).json({

                success: true,

                message:
                    "Student trained successfully.",

                data: aiResponse.data

            });

        }

        catch (error) {

            next(error);

        }

    }

}

module.exports = AIController;