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

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

        const cognitive_exercises = await db.cognitive_exercises.create(
            {
                id: data.id || undefined,
        
        exercise_name: data.exercise_name
        ||
        null
            ,
            
        exercise_type: data.exercise_type
        ||
        null
            ,
            
        instructions: data.instructions
        ||
        null
            ,
            
        difficulty_level: data.difficulty_level
        ||
        null
            ,
            
        max_score: data.max_score
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await cognitive_exercises.setProgram( data.program || null, {
            transaction,
        });
        
        await cognitive_exercises.setAccounts( data.accounts || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.cognitive_exercises.getTableName(),
                belongsToColumn: 'assets',
                belongsToId: cognitive_exercises.id,
            },
            data.assets,
            options,
        );
        

        return cognitive_exercises;
    }
    

    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 cognitive_exercisesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                exercise_name: item.exercise_name
            ||
            null
            ,
            
                exercise_type: item.exercise_type
            ||
            null
            ,
            
                instructions: item.instructions
            ||
            null
            ,
            
                difficulty_level: item.difficulty_level
            ||
            null
            ,
            
                max_score: item.max_score
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < cognitive_exercises.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.cognitive_exercises.getTableName(),
                    belongsToColumn: 'assets',
                    belongsToId: cognitive_exercises[i].id,
                },
                data[i].assets,
                options,
            );
        }
        

        return cognitive_exercises;
    }

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


        

        const updatePayload = {};
        
        if (data.exercise_name !== undefined) updatePayload.exercise_name = data.exercise_name;
        
        
        if (data.exercise_type !== undefined) updatePayload.exercise_type = data.exercise_type;
        
        
        if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
        
        
        if (data.difficulty_level !== undefined) updatePayload.difficulty_level = data.difficulty_level;
        
        
        if (data.max_score !== undefined) updatePayload.max_score = data.max_score;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.program !== undefined) {
            await cognitive_exercises.setProgram(
              
              data.program,
              
              { transaction }
            );
        }
        
        if (data.accounts !== undefined) {
            await cognitive_exercises.setAccounts(
              
              data.accounts,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.cognitive_exercises.getTableName(),
                belongsToColumn: 'assets',
                belongsToId: cognitive_exercises.id,
            },
            data.assets,
            options,
        );
        

        return cognitive_exercises;
    }

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

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

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


        return cognitive_exercises;
    }

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

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

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

        await cognitive_exercises.destroy({
            transaction
        });

        return cognitive_exercises;
    }

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

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

        if (!cognitive_exercises) {
            return cognitive_exercises;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.cognitive_attempts_exercise = await cognitive_exercises.getCognitive_attempts_exercise({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.program = await cognitive_exercises.getProgram({
            transaction
        });
        
        
        output.assets = await cognitive_exercises.getAssets({
            transaction
        });
        
        
        output.accounts = await cognitive_exercises.getAccounts({
            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 userAccounts = (user && user.accounts?.id) || null;
        

        
        if (userAccounts) {
            if (options?.currentUser?.accountsId) {
                where.accountsId = options.currentUser.accountsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

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



      {
        model: db.file,
        as: 'assets',
      },

    ];

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

            
            if (filter.exercise_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'cognitive_exercises',
                        'exercise_name',
                        filter.exercise_name,
                    ),
                };
            }
            
            if (filter.instructions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'cognitive_exercises',
                        'instructions',
                        filter.instructions,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.exercise_type) {
                where = {
                    ...where,
                exercise_type: filter.exercise_type,
            };
            }
            
            if (filter.difficulty_level) {
                where = {
                    ...where,
                difficulty_level: filter.difficulty_level,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      

      
      if (filter.accounts) {
        const listItems = filter.accounts.split('|').map(item => {
          return  Utils.uuid(item)
        });

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

        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.cognitive_exercises.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(
                        'cognitive_exercises',
                        'exercise_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

