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

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

        const mental_assessments = await db.mental_assessments.create(
            {
                id: data.id || undefined,
        
        assessment_type: data.assessment_type
        ||
        null
            ,
            
        taken_at: data.taken_at
        ||
        null
            ,
            
        score_total: data.score_total
        ||
        null
            ,
            
        responses_json: data.responses_json
        ||
        null
            ,
            
        interpretation_notes: data.interpretation_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return mental_assessments;
    }
    

    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 mental_assessmentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                assessment_type: item.assessment_type
            ||
            null
            ,
            
                taken_at: item.taken_at
            ||
            null
            ,
            
                score_total: item.score_total
            ||
            null
            ,
            
                responses_json: item.responses_json
            ||
            null
            ,
            
                interpretation_notes: item.interpretation_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return mental_assessments;
    }

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

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


        

        const updatePayload = {};
        
        if (data.assessment_type !== undefined) updatePayload.assessment_type = data.assessment_type;
        
        
        if (data.taken_at !== undefined) updatePayload.taken_at = data.taken_at;
        
        
        if (data.score_total !== undefined) updatePayload.score_total = data.score_total;
        
        
        if (data.responses_json !== undefined) updatePayload.responses_json = data.responses_json;
        
        
        if (data.interpretation_notes !== undefined) updatePayload.interpretation_notes = data.interpretation_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return mental_assessments;
    }

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

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

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


        return mental_assessments;
    }

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

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

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

        await mental_assessments.destroy({
            transaction
        });

        return mental_assessments;
    }

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

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

        if (!mental_assessments) {
            return mental_assessments;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await mental_assessments.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.responses_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'mental_assessments',
                        'responses_json',
                        filter.responses_json,
                    ),
                };
            }
            
            if (filter.interpretation_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'mental_assessments',
                        'interpretation_notes',
                        filter.interpretation_notes,
                    ),
                };
            }
            

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

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

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

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

            
            if (filter.assessment_type) {
                where = {
                    ...where,
                assessment_type: filter.assessment_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.mental_assessments.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(
                        'mental_assessments',
                        'interpretation_notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

