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

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

        const quiz_submissions = await db.quiz_submissions.create(
            {
                id: data.id || undefined,
        
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        score: data.score
        ||
        null
            ,
            
        is_passed: data.is_passed
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await quiz_submissions.setQuiz( data.quiz || null, {
            transaction,
        });
        
        await quiz_submissions.setUser( data.user || null, {
            transaction,
        });
        
        await quiz_submissions.setMission_attempt( data.mission_attempt || null, {
            transaction,
        });
        
        await quiz_submissions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return quiz_submissions;
    }
    

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

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

        // For each item created, replace relation files
        

        return quiz_submissions;
    }

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


        

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

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

        
        
        if (data.quiz !== undefined) {
            await quiz_submissions.setQuiz(
              
              data.quiz,
              
              { transaction }
            );
        }
        
        if (data.user !== undefined) {
            await quiz_submissions.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.mission_attempt !== undefined) {
            await quiz_submissions.setMission_attempt(
              
              data.mission_attempt,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await quiz_submissions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return quiz_submissions;
    }

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

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

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


        return quiz_submissions;
    }

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

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

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

        await quiz_submissions.destroy({
            transaction
        });

        return quiz_submissions;
    }

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

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

        if (!quiz_submissions) {
            return quiz_submissions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.quiz_answers_quiz_submission = await quiz_submissions.getQuiz_answers_quiz_submission({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.quiz = await quiz_submissions.getQuiz({
            transaction
        });
        
        
        output.user = await quiz_submissions.getUser({
            transaction
        });
        
        
        output.mission_attempt = await quiz_submissions.getMission_attempt({
            transaction
        });
        
        
        output.organizations = await quiz_submissions.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.quizzes,
        as: 'quiz',
        
        where: filter.quiz ? {
          [Op.or]: [
            { id: { [Op.in]: filter.quiz.split('|').map(term => Utils.uuid(term)) } },
            {
              quiz_title: {
                [Op.or]: filter.quiz.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.mission_attempts,
        as: 'mission_attempt',
        
        where: filter.mission_attempt ? {
          [Op.or]: [
            { id: { [Op.in]: filter.mission_attempt.split('|').map(term => Utils.uuid(term)) } },
            {
              attempt_status: {
                [Op.or]: filter.mission_attempt.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.submitted_atRange) {
                const [start, end] = filter.submitted_atRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    submitted_at: {
                    ...where.submitted_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

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


      

      

      

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

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

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

    
};

