
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class StudentsDBApi {
    

    
    static async create(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const students = await db.students.create(
            {
                id: data.id || undefined,
        
        full_name: data.full_name
        ||
        null
            ,
            
        student_code: data.student_code
        ||
        null
            ,
            
        gender: data.gender
        ||
        null
            ,
            
        date_of_birth: data.date_of_birth
        ||
        null
            ,
            
        guardian_name: data.guardian_name
        ||
        null
            ,
            
        guardian_phone: data.guardian_phone
        ||
        null
            ,
            
        address_text: data.address_text
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await students.setUser( data.user || null, {
            transaction,
        });
        
        await students.setCurrent_grade( data.current_grade || null, {
            transaction,
        });
        
        await students.setCurrent_stream( data.current_stream || null, {
            transaction,
        });
        

        

        

        return students;
    }
    

    static async bulkImport(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        // Prepare data - wrapping individual data transformations in a map() method
        const studentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                full_name: item.full_name
            ||
            null
            ,
            
                student_code: item.student_code
            ||
            null
            ,
            
                gender: item.gender
            ||
            null
            ,
            
                date_of_birth: item.date_of_birth
            ||
            null
            ,
            
                guardian_name: item.guardian_name
            ||
            null
            ,
            
                guardian_phone: item.guardian_phone
            ||
            null
            ,
            
                address_text: item.address_text
            ||
            null
            ,
            
                active: item.active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const students = await db.students.bulkCreate(studentsData, { transaction });

        // For each item created, replace relation files
        

        return students;
    }

    static async update(id, data,  options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;
        

        const students = await db.students.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.full_name !== undefined) updatePayload.full_name = data.full_name;
        
        
        if (data.student_code !== undefined) updatePayload.student_code = data.student_code;
        
        
        if (data.gender !== undefined) updatePayload.gender = data.gender;
        
        
        if (data.date_of_birth !== undefined) updatePayload.date_of_birth = data.date_of_birth;
        
        
        if (data.guardian_name !== undefined) updatePayload.guardian_name = data.guardian_name;
        
        
        if (data.guardian_phone !== undefined) updatePayload.guardian_phone = data.guardian_phone;
        
        
        if (data.address_text !== undefined) updatePayload.address_text = data.address_text;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

        await students.update(updatePayload, {transaction});

        
        
        if (data.user !== undefined) {
            await students.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.current_grade !== undefined) {
            await students.setCurrent_grade(
              
              data.current_grade,
              
              { transaction }
            );
        }
        
        if (data.current_stream !== undefined) {
            await students.setCurrent_stream(
              
              data.current_stream,
              
              { transaction }
            );
        }
        

        
        

        

        return students;
    }

    static async deleteByIds(ids, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const students = await db.students.findAll({
            where: {
                id: {
                    [Op.in]: ids,
                },
            },
            transaction,
        });

        await db.sequelize.transaction(async (transaction) => {
            for (const record of students) {
                await record.update(
                    {deletedBy: currentUser.id},
                    {transaction}
                );
            }
            for (const record of students) {
                await record.destroy({transaction});
            }
        });


        return students;
    }

    static async remove(id, options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;

        const students = await db.students.findByPk(id, options);

        await students.update({
            deletedBy: currentUser.id
        }, {
            transaction,
        });

        await students.destroy({
            transaction
        });

        return students;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;

        const students = await db.students.findOne(
            { where },
            { transaction },
        );

        if (!students) {
            return students;
        }

        const output = students.get({plain: true});

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.enrollments_student = await students.getEnrollments_student({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.exam_results_student = await students.getExam_results_student({
            transaction
        });
        
        
        
        output.attendance_records_student = await students.getAttendance_records_student({
            transaction
        });
        
        
        
        
        output.assignment_submissions_student = await students.getAssignment_submissions_student({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.top_student_features_student = await students.getTop_student_features_student({
            transaction
        });
        
        
        
        output.user = await students.getUser({
            transaction
        });
        
        
        output.current_grade = await students.getCurrent_grade({
            transaction
        });
        
        
        output.current_stream = await students.getCurrent_stream({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.grades,
        as: 'current_grade',
        
        where: filter.current_grade ? {
          [Op.or]: [
            { id: { [Op.in]: filter.current_grade.split('|').map(term => Utils.uuid(term)) } },
            {
              label: {
                [Op.or]: filter.current_grade.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.streams,
        as: 'current_stream',
        
        where: filter.current_stream ? {
          [Op.or]: [
            { id: { [Op.in]: filter.current_stream.split('|').map(term => Utils.uuid(term)) } },
            {
              name_en: {
                [Op.or]: filter.current_stream.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

        if (filter) {
            if (filter.id) {
                where = {
                    ...where,
                    ['id']: Utils.uuid(filter.id),
                };
            }

            
            if (filter.full_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'students',
                        'full_name',
                        filter.full_name,
                    ),
                };
            }
            
            if (filter.student_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'students',
                        'student_code',
                        filter.student_code,
                    ),
                };
            }
            
            if (filter.guardian_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'students',
                        'guardian_name',
                        filter.guardian_name,
                    ),
                };
            }
            
            if (filter.guardian_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'students',
                        'guardian_phone',
                        filter.guardian_phone,
                    ),
                };
            }
            
            if (filter.address_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'students',
                        'address_text',
                        filter.address_text,
                    ),
                };
            }
            

            
            

            
            if (filter.date_of_birthRange) {
                const [start, end] = filter.date_of_birthRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    date_of_birth: {
                    ...where.date_of_birth,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    date_of_birth: {
                    ...where.date_of_birth,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.gender) {
                where = {
                    ...where,
                gender: filter.gender,
            };
            }
            
            if (filter.active) {
                where = {
                    ...where,
                active: filter.active,
            };
            }
            


      

      

      



            if (filter.createdAtRange) {
                const [start, end] = filter.createdAtRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.gte]: start,
                        },
                    };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.lte]: end,
                        },
                    };
                }
            }
        }
        

        

        const queryOptions = {
            where,
            include,
            distinct: true,
            order: filter.field && filter.sort
                ? [[filter.field, filter.sort]]
                : [['createdAt', 'desc']],
            transaction: options?.transaction,
            logging: console.log
        };

        if (!options?.countOnly) {
            queryOptions.limit = limit ? Number(limit) : undefined;
            queryOptions.offset = offset ? Number(offset) : undefined;
        }

        try {
            const { rows, count } = await db.students.findAndCountAll(queryOptions);

            return {
                rows: options?.countOnly ? [] : rows,
                count: count
            };
        } catch (error) {
            console.error('Error executing query:', error);
            throw error;
        }
    }

    static async findAllAutocomplete(query, limit, offset, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'students',
                        'full_name',
                        query,
                    ),
                ],
            };
        }

        const records = await db.students.findAll({
            attributes: [ 'id', 'full_name' ],
            where,
            limit: limit ? Number(limit) : undefined,
            offset: offset ? Number(offset) : undefined,
            orderBy: [['full_name', 'ASC']],
        });

        return records.map((record) => ({
            id: record.id,
            label: record.full_name,
        }));
    }

    
};

