/**
 * ===============================================
 * Smart Attendance System
 * Embedding Repository
 * ===============================================
 * Handles all database operations related to
 * student face embeddings.
 * ===============================================
 */

const db = require("../config/db");

/**
 * Save a new embedding
 */
async function create(data) {

    const sql = `
        INSERT INTO student_face_embeddings
        (
            student_id,
            average_embedding,
            trained_images,
            embedding_dimension,
            ai_model,
            created_at
        )
        VALUES (?, ?, ?, ?, ?, NOW())
    `;

    const values = [

        data.student_id,

        JSON.stringify(data.average_embedding),

        data.trained_images,

        data.embedding_dimension,

        data.ai_model

    ];

    const [result] = await db.execute(

        sql,

        values

    );

    return result;

}

/**
 * Update existing embedding
 */
async function update(studentId, data) {

    const sql = `
        UPDATE student_face_embeddings
        SET
            average_embedding=?,
            trained_images=?,
            embedding_dimension=?,
            ai_model=?,
            updated_at=NOW()
        WHERE student_id=?
    `;

    const values = [

        JSON.stringify(data.average_embedding),

        data.trained_images,

        data.embedding_dimension,

        data.ai_model,

        studentId

    ];

    const [result] = await db.execute(

        sql,

        values

    );

    return result;

}

/**
 * Find by Student ID
 */
async function findByStudentId(studentId) {

    const sql = `
        SELECT *
        FROM student_face_embeddings
        WHERE student_id=?
        LIMIT 1
    `;

    const [rows] = await db.execute(

        sql,

        [studentId]

    );

    if (!rows.length) {

        return null;

    }

    rows[0].average_embedding = JSON.parse(

        rows[0].average_embedding

    );

    return rows[0];

}

/**
 * Get All Embeddings
 */
async function findAll() {

    const sql = `
        SELECT *
        FROM student_face_embeddings
    `;

    const [rows] = await db.execute(sql);

    return rows.map(row => ({

        ...row,

        average_embedding: JSON.parse(

            row.average_embedding

        )

    }));

}

/**
 * Delete Embedding
 */
async function remove(studentId) {

    const sql = `
        DELETE
        FROM student_face_embeddings
        WHERE student_id=?
    `;

    const [result] = await db.execute(

        sql,

        [studentId]

    );

    return result;

}

module.exports = {

    create,

    update,

    findByStudentId,

    findAll,

    remove

};