
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 Top_student_featuresDBApi {
    

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

        const top_student_features = await db.top_student_features.create(
            {
                id: data.id || undefined,
        
        total_score: data.total_score
        ||
        null
            ,
            
        rank: data.rank
        ||
        null
            ,
            
        consent_to_publish: data.consent_to_publish
        ||
        false
        
            ,
            
        published: data.published
        ||
        false
        
            ,
            
        note: data.note
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await top_student_features.setExam( data.exam || null, {
            transaction,
        });
        
        await top_student_features.setStudent( data.student || null, {
            transaction,
        });
        

        

        

        return top_student_features;
    }
    

    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 top_student_featuresData = data.map((item, index) => ({
                id: item.id || undefined,
                
                total_score: item.total_score
            ||
            null
            ,
            
                rank: item.rank
            ||
            null
            ,
            
                consent_to_publish: item.consent_to_publish
            ||
            false
        
            ,
            
                published: item.published
            ||
            false
        
            ,
            
                note: item.note
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return top_student_features;
    }

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

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


        

        const updatePayload = {};
        
        if (data.total_score !== undefined) updatePayload.total_score = data.total_score;
        
        
        if (data.rank !== undefined) updatePayload.rank = data.rank;
        
        
        if (data.consent_to_publish !== undefined) updatePayload.consent_to_publish = data.consent_to_publish;
        
        
        if (data.published !== undefined) updatePayload.published = data.published;
        
        
        if (data.note !== undefined) updatePayload.note = data.note;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.exam !== undefined) {
            await top_student_features.setExam(
              
              data.exam,
              
              { transaction }
            );
        }
        
        if (data.student !== undefined) {
            await top_student_features.setStudent(
              
              data.student,
              
              { transaction }
            );
        }
        

        
        

        

        return top_student_features;
    }

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

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

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


        return top_student_features;
    }

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

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

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

        await top_student_features.destroy({
            transaction
        });

        return top_student_features;
    }

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

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

        if (!top_student_features) {
            return top_student_features;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.exam = await top_student_features.getExam({
            transaction
        });
        
        
        output.student = await top_student_features.getStudent({
            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.exams,
        as: 'exam',
        
        where: filter.exam ? {
          [Op.or]: [
            { id: { [Op.in]: filter.exam.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.exam.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.note) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'top_student_features',
                        'note',
                        filter.note,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    total_score: {
                    ...where.total_score,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.rankRange) {
                const [start, end] = filter.rankRange;

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

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

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

            
            if (filter.consent_to_publish) {
                where = {
                    ...where,
                consent_to_publish: filter.consent_to_publish,
            };
            }
            
            if (filter.published) {
                where = {
                    ...where,
                published: filter.published,
            };
            }
            


      

      



            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.top_student_features.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(
                        'top_student_features',
                        'note',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

