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

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

        const cognitive_tests = await db.cognitive_tests.create(
            {
                id: data.id || undefined,
        
        test_type: data.test_type
        ||
        null
            ,
            
        taken_at: data.taken_at
        ||
        null
            ,
            
        score: data.score
        ||
        null
            ,
            
        duration_seconds: data.duration_seconds
        ||
        null
            ,
            
        details_json: data.details_json
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await cognitive_tests.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return cognitive_tests;
    }
    

    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_testsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                test_type: item.test_type
            ||
            null
            ,
            
                taken_at: item.taken_at
            ||
            null
            ,
            
                score: item.score
            ||
            null
            ,
            
                duration_seconds: item.duration_seconds
            ||
            null
            ,
            
                details_json: item.details_json
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return cognitive_tests;
    }

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

        const cognitive_tests = await db.cognitive_tests.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.test_type !== undefined) updatePayload.test_type = data.test_type;
        
        
        if (data.taken_at !== undefined) updatePayload.taken_at = data.taken_at;
        
        
        if (data.score !== undefined) updatePayload.score = data.score;
        
        
        if (data.duration_seconds !== undefined) updatePayload.duration_seconds = data.duration_seconds;
        
        
        if (data.details_json !== undefined) updatePayload.details_json = data.details_json;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await cognitive_tests.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

        

        return cognitive_tests;
    }

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

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

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


        return cognitive_tests;
    }

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

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

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

        await cognitive_tests.destroy({
            transaction
        });

        return cognitive_tests;
    }

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

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

        if (!cognitive_tests) {
            return cognitive_tests;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await cognitive_tests.getUser({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            taken_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    taken_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    taken_at: {
                    ...where.taken_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.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.test_type) {
                where = {
                    ...where,
                test_type: filter.test_type,
            };
            }
            


      



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

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

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

    
};

