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

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

        const flexibility_assessments = await db.flexibility_assessments.create(
            {
                id: data.id || undefined,
        
        assessed_at: data.assessed_at
        ||
        null
            ,
            
        sit_and_reach_score: data.sit_and_reach_score
        ||
        null
            ,
            
        shoulder_mobility_score: data.shoulder_mobility_score
        ||
        null
            ,
            
        hip_flexor_score: data.hip_flexor_score
        ||
        null
            ,
            
        hamstring_score: data.hamstring_score
        ||
        null
            ,
            
        ankle_dorsiflexion_score: data.ankle_dorsiflexion_score
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return flexibility_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 flexibility_assessmentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                assessed_at: item.assessed_at
            ||
            null
            ,
            
                sit_and_reach_score: item.sit_and_reach_score
            ||
            null
            ,
            
                shoulder_mobility_score: item.shoulder_mobility_score
            ||
            null
            ,
            
                hip_flexor_score: item.hip_flexor_score
            ||
            null
            ,
            
                hamstring_score: item.hamstring_score
            ||
            null
            ,
            
                ankle_dorsiflexion_score: item.ankle_dorsiflexion_score
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return flexibility_assessments;
    }

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

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


        

        const updatePayload = {};
        
        if (data.assessed_at !== undefined) updatePayload.assessed_at = data.assessed_at;
        
        
        if (data.sit_and_reach_score !== undefined) updatePayload.sit_and_reach_score = data.sit_and_reach_score;
        
        
        if (data.shoulder_mobility_score !== undefined) updatePayload.shoulder_mobility_score = data.shoulder_mobility_score;
        
        
        if (data.hip_flexor_score !== undefined) updatePayload.hip_flexor_score = data.hip_flexor_score;
        
        
        if (data.hamstring_score !== undefined) updatePayload.hamstring_score = data.hamstring_score;
        
        
        if (data.ankle_dorsiflexion_score !== undefined) updatePayload.ankle_dorsiflexion_score = data.ankle_dorsiflexion_score;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return flexibility_assessments;
    }

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

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

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


        return flexibility_assessments;
    }

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

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

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

        await flexibility_assessments.destroy({
            transaction
        });

        return flexibility_assessments;
    }

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

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

        if (!flexibility_assessments) {
            return flexibility_assessments;
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            


      



            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.flexibility_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(
                        'flexibility_assessments',
                        'notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

