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

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

        const cognitive_attempts = await db.cognitive_attempts.create(
            {
                id: data.id || undefined,
        
        attempted_at: data.attempted_at
        ||
        null
            ,
            
        score: data.score
        ||
        null
            ,
            
        accuracy: data.accuracy
        ||
        null
            ,
            
        duration_seconds: data.duration_seconds
        ||
        null
            ,
            
        result: data.result
        ||
        null
            ,
            
        raw_response: data.raw_response
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await cognitive_attempts.setSession( data.session || null, {
            transaction,
        });
        
        await cognitive_attempts.setExercise( data.exercise || null, {
            transaction,
        });
        
        await cognitive_attempts.setAccounts( data.accounts || null, {
            transaction,
        });
        

        

        

        return cognitive_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 cognitive_attemptsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                attempted_at: item.attempted_at
            ||
            null
            ,
            
                score: item.score
            ||
            null
            ,
            
                accuracy: item.accuracy
            ||
            null
            ,
            
                duration_seconds: item.duration_seconds
            ||
            null
            ,
            
                result: item.result
            ||
            null
            ,
            
                raw_response: item.raw_response
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.attempted_at !== undefined) updatePayload.attempted_at = data.attempted_at;
        
        
        if (data.score !== undefined) updatePayload.score = data.score;
        
        
        if (data.accuracy !== undefined) updatePayload.accuracy = data.accuracy;
        
        
        if (data.duration_seconds !== undefined) updatePayload.duration_seconds = data.duration_seconds;
        
        
        if (data.result !== undefined) updatePayload.result = data.result;
        
        
        if (data.raw_response !== undefined) updatePayload.raw_response = data.raw_response;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.session !== undefined) {
            await cognitive_attempts.setSession(
              
              data.session,
              
              { transaction }
            );
        }
        
        if (data.exercise !== undefined) {
            await cognitive_attempts.setExercise(
              
              data.exercise,
              
              { transaction }
            );
        }
        
        if (data.accounts !== undefined) {
            await cognitive_attempts.setAccounts(
              
              data.accounts,
              
              { transaction }
            );
        }
        

        
        

        

        return cognitive_attempts;
    }

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

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

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


        return cognitive_attempts;
    }

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

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

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

        await cognitive_attempts.destroy({
            transaction
        });

        return cognitive_attempts;
    }

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

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

        if (!cognitive_attempts) {
            return cognitive_attempts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.session = await cognitive_attempts.getSession({
            transaction
        });
        
        
        output.exercise = await cognitive_attempts.getExercise({
            transaction
        });
        
        
        output.accounts = await cognitive_attempts.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_sessions,
        as: 'session',
        
        where: filter.session ? {
          [Op.or]: [
            { id: { [Op.in]: filter.session.split('|').map(term => Utils.uuid(term)) } },
            {
              completion_status: {
                [Op.or]: filter.session.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.raw_response) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'cognitive_attempts',
                        'raw_response',
                        filter.raw_response,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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


      

      

      
      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_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(
                        'cognitive_attempts',
                        'result',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

