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

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

        const exam_results = await db.exam_results.create(
            {
                id: data.id || undefined,
        
        score: data.score
        ||
        null
            ,
            
        out_of: data.out_of
        ||
        null
            ,
            
        result_status: data.result_status
        ||
        null
            ,
            
        entered_at: data.entered_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await exam_results.setExam( data.exam || null, {
            transaction,
        });
        
        await exam_results.setStudent( data.student || null, {
            transaction,
        });
        
        await exam_results.setSubject( data.subject || null, {
            transaction,
        });
        
        await exam_results.setEntered_by( data.entered_by || null, {
            transaction,
        });
        

        

        

        return exam_results;
    }
    

    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_resultsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                score: item.score
            ||
            null
            ,
            
                out_of: item.out_of
            ||
            null
            ,
            
                result_status: item.result_status
            ||
            null
            ,
            
                entered_at: item.entered_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return exam_results;
    }

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

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


        

        const updatePayload = {};
        
        if (data.score !== undefined) updatePayload.score = data.score;
        
        
        if (data.out_of !== undefined) updatePayload.out_of = data.out_of;
        
        
        if (data.result_status !== undefined) updatePayload.result_status = data.result_status;
        
        
        if (data.entered_at !== undefined) updatePayload.entered_at = data.entered_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.exam !== undefined) {
            await exam_results.setExam(
              
              data.exam,
              
              { transaction }
            );
        }
        
        if (data.student !== undefined) {
            await exam_results.setStudent(
              
              data.student,
              
              { transaction }
            );
        }
        
        if (data.subject !== undefined) {
            await exam_results.setSubject(
              
              data.subject,
              
              { transaction }
            );
        }
        
        if (data.entered_by !== undefined) {
            await exam_results.setEntered_by(
              
              data.entered_by,
              
              { transaction }
            );
        }
        

        
        

        

        return exam_results;
    }

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

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

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


        return exam_results;
    }

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

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

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

        await exam_results.destroy({
            transaction
        });

        return exam_results;
    }

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

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

        if (!exam_results) {
            return exam_results;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.exam = await exam_results.getExam({
            transaction
        });
        
        
        output.student = await exam_results.getStudent({
            transaction
        });
        
        
        output.subject = await exam_results.getSubject({
            transaction
        });
        
        
        output.entered_by = await exam_results.getEntered_by({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            

            
            

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

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

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

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

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

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

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

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

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


      

      

      

      



            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_results.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_results',
                        'result_status',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

