
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,
        
        status: data.status
        ||
        null
            ,
            
        score_percent: data.score_percent
        ||
        null
            ,
            
        correct_count: data.correct_count
        ||
        null
            ,
            
        total_count: data.total_count
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        coins_awarded: data.coins_awarded
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await quiz_attempts.setUser( data.user || null, {
            transaction,
        });
        
        await quiz_attempts.setQuiz_definition( data.quiz_definition || 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,
                
                status: item.status
            ||
            null
            ,
            
                score_percent: item.score_percent
            ||
            null
            ,
            
                correct_count: item.correct_count
            ||
            null
            ,
            
                total_count: item.total_count
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                coins_awarded: item.coins_awarded
            ||
            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 quiz_attempts = await db.quiz_attempts.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        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;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.coins_awarded !== undefined) updatePayload.coins_awarded = data.coins_awarded;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await quiz_attempts.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.quiz_definition !== undefined) {
            await quiz_attempts.setQuiz_definition(
              
              data.quiz_definition,
              
              { 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.user = await quiz_attempts.getUser({
            transaction
        });
        
        
        output.quiz_definition = await quiz_attempts.getQuiz_definition({
            transaction
        });
        
        

        return output;
    }

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

        

        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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



    ];

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

            

            
            

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

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

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

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

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


      

      



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

        

        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, ) {
        let where = {};
        
        

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

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

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

    
};

