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

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

        const quiz_attempts = await db.quiz_attempts.create(
            {
                id: data.id || undefined,
        
        started_at: data.started_at
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        score_percent: data.score_percent
        ||
        null
            ,
            
        correct_count: data.correct_count
        ||
        null
            ,
            
        total_count: data.total_count
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await quiz_attempts.setQuiz( data.quiz || null, {
            transaction,
        });
        
        await quiz_attempts.setUser( data.user || null, {
            transaction,
        });
        
        await quiz_attempts.setSession( data.session || null, {
            transaction,
        });
        
        await quiz_attempts.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return quiz_attempts;
    }
    

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

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

        // For each item created, replace relation files
        

        return quiz_attempts;
    }

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


        

        const updatePayload = {};
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.score_percent !== undefined) updatePayload.score_percent = data.score_percent;
        
        
        if (data.correct_count !== undefined) updatePayload.correct_count = data.correct_count;
        
        
        if (data.total_count !== undefined) updatePayload.total_count = data.total_count;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.quiz !== undefined) {
            await quiz_attempts.setQuiz(
              
              data.quiz,
              
              { transaction }
            );
        }
        
        if (data.user !== undefined) {
            await quiz_attempts.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.session !== undefined) {
            await quiz_attempts.setSession(
              
              data.session,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await quiz_attempts.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return quiz_attempts;
    }

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

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

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


        return quiz_attempts;
    }

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

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

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

        await quiz_attempts.destroy({
            transaction
        });

        return quiz_attempts;
    }

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

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

        if (!quiz_attempts) {
            return quiz_attempts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.quiz = await quiz_attempts.getQuiz({
            transaction
        });
        
        
        output.user = await quiz_attempts.getUser({
            transaction
        });
        
        
        output.session = await quiz_attempts.getSession({
            transaction
        });
        
        
        output.organizations = await quiz_attempts.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)) } },
            {
              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.study_sessions,
        as: 'session',
        
        where: filter.session ? {
          [Op.or]: [
            { id: { [Op.in]: filter.session.split('|').map(term => Utils.uuid(term)) } },
            {
              mode: {
                [Op.or]: filter.session.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.started_atRange) {
                const [start, end] = filter.started_atRange;

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

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

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

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

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

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

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

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

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

            


      

      

      

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

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

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

    
};

