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

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

        const exam_question_choices = await db.exam_question_choices.create(
            {
                id: data.id || undefined,
        
        choice_label: data.choice_label
        ||
        null
            ,
            
        choice_text: data.choice_text
        ||
        null
            ,
            
        is_correct: data.is_correct
        ||
        false
        
            ,
            
        order_number: data.order_number
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await exam_question_choices.setExam_question( data.exam_question || null, {
            transaction,
        });
        
        await exam_question_choices.setSchools( data.schools || null, {
            transaction,
        });
        

        

        

        return exam_question_choices;
    }
    

    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_question_choicesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                choice_label: item.choice_label
            ||
            null
            ,
            
                choice_text: item.choice_text
            ||
            null
            ,
            
                is_correct: item.is_correct
            ||
            false
        
            ,
            
                order_number: item.order_number
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return exam_question_choices;
    }

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

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


        

        const updatePayload = {};
        
        if (data.choice_label !== undefined) updatePayload.choice_label = data.choice_label;
        
        
        if (data.choice_text !== undefined) updatePayload.choice_text = data.choice_text;
        
        
        if (data.is_correct !== undefined) updatePayload.is_correct = data.is_correct;
        
        
        if (data.order_number !== undefined) updatePayload.order_number = data.order_number;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.exam_question !== undefined) {
            await exam_question_choices.setExam_question(
              
              data.exam_question,
              
              { transaction }
            );
        }
        
        if (data.schools !== undefined) {
            await exam_question_choices.setSchools(
              
              data.schools,
              
              { transaction }
            );
        }
        

        
        

        

        return exam_question_choices;
    }

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

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

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


        return exam_question_choices;
    }

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

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

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

        await exam_question_choices.destroy({
            transaction
        });

        return exam_question_choices;
    }

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

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

        if (!exam_question_choices) {
            return exam_question_choices;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.exam_answers_selected_choice = await exam_question_choices.getExam_answers_selected_choice({
            transaction
        });
        
        
        
        
        
        
        
        output.exam_question = await exam_question_choices.getExam_question({
            transaction
        });
        
        
        output.schools = await exam_question_choices.getSchools({
            transaction
        });
        
        

        return output;
    }

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

        
        const user = (options && options.currentUser) || null;
        const userSchools = (user && user.schools?.id) || null;
        

        
        if (userSchools) {
            if (options?.currentUser?.schoolsId) {
                where.schoolsId = options.currentUser.schoolsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

      {
        model: db.schools,
        as: 'schools',
        
      },



    ];

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

            
            if (filter.choice_label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'exam_question_choices',
                        'choice_label',
                        filter.choice_label,
                    ),
                };
            }
            
            if (filter.choice_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'exam_question_choices',
                        'choice_text',
                        filter.choice_text,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      
      if (filter.schools) {
        const listItems = filter.schools.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          schoolsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.schoolsId;
        }
        

        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_question_choices.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

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

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

    
};

