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

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

        const exam_performance_summaries = await db.exam_performance_summaries.create(
            {
                id: data.id || undefined,
        
        average_score: data.average_score
        ||
        null
            ,
            
        highest_score: data.highest_score
        ||
        null
            ,
            
        lowest_score: data.lowest_score
        ||
        null
            ,
            
        pass_rate: data.pass_rate
        ||
        null
            ,
            
        student_count: data.student_count
        ||
        null
            ,
            
        published: data.published
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await exam_performance_summaries.setExam( data.exam || null, {
            transaction,
        });
        

        

        

        return exam_performance_summaries;
    }
    

    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 exam_performance_summariesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                average_score: item.average_score
            ||
            null
            ,
            
                highest_score: item.highest_score
            ||
            null
            ,
            
                lowest_score: item.lowest_score
            ||
            null
            ,
            
                pass_rate: item.pass_rate
            ||
            null
            ,
            
                student_count: item.student_count
            ||
            null
            ,
            
                published: item.published
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return exam_performance_summaries;
    }

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

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


        

        const updatePayload = {};
        
        if (data.average_score !== undefined) updatePayload.average_score = data.average_score;
        
        
        if (data.highest_score !== undefined) updatePayload.highest_score = data.highest_score;
        
        
        if (data.lowest_score !== undefined) updatePayload.lowest_score = data.lowest_score;
        
        
        if (data.pass_rate !== undefined) updatePayload.pass_rate = data.pass_rate;
        
        
        if (data.student_count !== undefined) updatePayload.student_count = data.student_count;
        
        
        if (data.published !== undefined) updatePayload.published = data.published;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return exam_performance_summaries;
    }

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

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

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


        return exam_performance_summaries;
    }

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

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

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

        await exam_performance_summaries.destroy({
            transaction
        });

        return exam_performance_summaries;
    }

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

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

        if (!exam_performance_summaries) {
            return exam_performance_summaries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.exam = await exam_performance_summaries.getExam({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
};

