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

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

        const quiz_answers = await db.quiz_answers.create(
            {
                id: data.id || undefined,
        
        answer_text: data.answer_text
        ||
        null
            ,
            
        is_correct: data.is_correct
        ||
        false
        
            ,
            
        points_earned: data.points_earned
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await quiz_answers.setQuiz_submission( data.quiz_submission || null, {
            transaction,
        });
        
        await quiz_answers.setQuiz_question( data.quiz_question || null, {
            transaction,
        });
        
        await quiz_answers.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

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

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

        // For each item created, replace relation files
        

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


        

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

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

        
        
        if (data.quiz_submission !== undefined) {
            await quiz_answers.setQuiz_submission(
              
              data.quiz_submission,
              
              { transaction }
            );
        }
        
        if (data.quiz_question !== undefined) {
            await quiz_answers.setQuiz_question(
              
              data.quiz_question,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await quiz_answers.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return quiz_answers;
    }

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

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

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


        return quiz_answers;
    }

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

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

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

        await quiz_answers.destroy({
            transaction
        });

        return quiz_answers;
    }

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

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

        if (!quiz_answers) {
            return quiz_answers;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.quiz_submission = await quiz_answers.getQuiz_submission({
            transaction
        });
        
        
        output.quiz_question = await quiz_answers.getQuiz_question({
            transaction
        });
        
        
        output.organizations = await quiz_answers.getOrganizations({
            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 userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

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

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



    ];

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

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

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    points_earned: {
                    ...where.points_earned,
                            [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.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[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.organizationsId;
        }
        

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

        const records = await db.quiz_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,
        }));
    }

    
};

