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

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

        const exam_answers = await db.exam_answers.create(
            {
                id: data.id || undefined,
        
        answer_text: data.answer_text
        ||
        null
            ,
            
        score: data.score
        ||
        null
            ,
            
        graded_at: data.graded_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await exam_answers.setExam_attempt( data.exam_attempt || null, {
            transaction,
        });
        
        await exam_answers.setExam_question( data.exam_question || null, {
            transaction,
        });
        
        await exam_answers.setSelected_choice( data.selected_choice || null, {
            transaction,
        });
        
        await exam_answers.setGraded_by( data.graded_by || null, {
            transaction,
        });
        
        await exam_answers.setSchools( data.schools || null, {
            transaction,
        });
        

        

        

        return exam_answers;
    }
    

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

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

        // For each item created, replace relation files
        

        return exam_answers;
    }

    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_answers = await db.exam_answers.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.answer_text !== undefined) updatePayload.answer_text = data.answer_text;
        
        
        if (data.score !== undefined) updatePayload.score = data.score;
        
        
        if (data.graded_at !== undefined) updatePayload.graded_at = data.graded_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.exam_attempt !== undefined) {
            await exam_answers.setExam_attempt(
              
              data.exam_attempt,
              
              { transaction }
            );
        }
        
        if (data.exam_question !== undefined) {
            await exam_answers.setExam_question(
              
              data.exam_question,
              
              { transaction }
            );
        }
        
        if (data.selected_choice !== undefined) {
            await exam_answers.setSelected_choice(
              
              data.selected_choice,
              
              { transaction }
            );
        }
        
        if (data.graded_by !== undefined) {
            await exam_answers.setGraded_by(
              
              data.graded_by,
              
              { transaction }
            );
        }
        
        if (data.schools !== undefined) {
            await exam_answers.setSchools(
              
              data.schools,
              
              { transaction }
            );
        }
        

        
        

        

        return exam_answers;
    }

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

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

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


        return exam_answers;
    }

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

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

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

        await exam_answers.destroy({
            transaction
        });

        return exam_answers;
    }

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

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

        if (!exam_answers) {
            return exam_answers;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.exam_attempt = await exam_answers.getExam_attempt({
            transaction
        });
        
        
        output.exam_question = await exam_answers.getExam_question({
            transaction
        });
        
        
        output.selected_choice = await exam_answers.getSelected_choice({
            transaction
        });
        
        
        output.graded_by = await exam_answers.getGraded_by({
            transaction
        });
        
        
        output.schools = await exam_answers.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_attempts,
        as: 'exam_attempt',
        
        where: filter.exam_attempt ? {
          [Op.or]: [
            { id: { [Op.in]: filter.exam_attempt.split('|').map(term => Utils.uuid(term)) } },
            {
              status: {
                [Op.or]: filter.exam_attempt.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        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.exam_question_choices,
        as: 'selected_choice',
        
        where: filter.selected_choice ? {
          [Op.or]: [
            { id: { [Op.in]: filter.selected_choice.split('|').map(term => Utils.uuid(term)) } },
            {
              choice_label: {
                [Op.or]: filter.selected_choice.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'graded_by',
        
        where: filter.graded_by ? {
          [Op.or]: [
            { id: { [Op.in]: filter.graded_by.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.graded_by.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.answer_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'exam_answers',
                        'answer_text',
                        filter.answer_text,
                    ),
                };
            }
            

            
            

            
            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.graded_atRange) {
                const [start, end] = filter.graded_atRange;

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

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

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

            


      

      

      

      

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

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

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

    
};

