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

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

        const mission_attempts = await db.mission_attempts.create(
            {
                id: data.id || undefined,
        
        attempt_status: data.attempt_status
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
        score: data.score
        ||
        null
            ,
            
        points_earned: data.points_earned
        ||
        null
            ,
            
        coins_earned: data.coins_earned
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await mission_attempts.setMission( data.mission || null, {
            transaction,
        });
        
        await mission_attempts.setUser( data.user || null, {
            transaction,
        });
        
        await mission_attempts.setEnrollment( data.enrollment || null, {
            transaction,
        });
        
        await mission_attempts.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return mission_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 mission_attemptsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                attempt_status: item.attempt_status
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                completed_at: item.completed_at
            ||
            null
            ,
            
                score: item.score
            ||
            null
            ,
            
                points_earned: item.points_earned
            ||
            null
            ,
            
                coins_earned: item.coins_earned
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.attempt_status !== undefined) updatePayload.attempt_status = data.attempt_status;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        if (data.score !== undefined) updatePayload.score = data.score;
        
        
        if (data.points_earned !== undefined) updatePayload.points_earned = data.points_earned;
        
        
        if (data.coins_earned !== undefined) updatePayload.coins_earned = data.coins_earned;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.mission !== undefined) {
            await mission_attempts.setMission(
              
              data.mission,
              
              { transaction }
            );
        }
        
        if (data.user !== undefined) {
            await mission_attempts.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.enrollment !== undefined) {
            await mission_attempts.setEnrollment(
              
              data.enrollment,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await mission_attempts.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return mission_attempts;
    }

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

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

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


        return mission_attempts;
    }

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

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

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

        await mission_attempts.destroy({
            transaction
        });

        return mission_attempts;
    }

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

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

        if (!mission_attempts) {
            return mission_attempts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.quiz_submissions_mission_attempt = await mission_attempts.getQuiz_submissions_mission_attempt({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.mission = await mission_attempts.getMission({
            transaction
        });
        
        
        output.user = await mission_attempts.getUser({
            transaction
        });
        
        
        output.enrollment = await mission_attempts.getEnrollment({
            transaction
        });
        
        
        output.organizations = await mission_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.missions,
        as: 'mission',
        
        where: filter.mission ? {
          [Op.or]: [
            { id: { [Op.in]: filter.mission.split('|').map(term => Utils.uuid(term)) } },
            {
              mission_title: {
                [Op.or]: filter.mission.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.enrollments,
        as: 'enrollment',
        
        where: filter.enrollment ? {
          [Op.or]: [
            { id: { [Op.in]: filter.enrollment.split('|').map(term => Utils.uuid(term)) } },
            {
              enrollment_status: {
                [Op.or]: filter.enrollment.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.completed_atRange) {
                const [start, end] = filter.completed_atRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    completed_at: {
                    ...where.completed_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.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.coins_earnedRange) {
                const [start, end] = filter.coins_earnedRange;

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

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

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

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


      

      

      

      
      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.mission_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(
                        'mission_attempts',
                        'attempt_status',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

