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

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

        const physio_exercises = await db.physio_exercises.create(
            {
                id: data.id || undefined,
        
        sets: data.sets
        ||
        null
            ,
            
        reps: data.reps
        ||
        null
            ,
            
        progression_notes: data.progression_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await physio_exercises.setInjury( data.injury || null, {
            transaction,
        });
        
        await physio_exercises.setExercise( data.exercise || null, {
            transaction,
        });
        

        

        

        return physio_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 physio_exercisesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                sets: item.sets
            ||
            null
            ,
            
                reps: item.reps
            ||
            null
            ,
            
                progression_notes: item.progression_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return physio_exercises;
    }

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

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


        

        const updatePayload = {};
        
        if (data.sets !== undefined) updatePayload.sets = data.sets;
        
        
        if (data.reps !== undefined) updatePayload.reps = data.reps;
        
        
        if (data.progression_notes !== undefined) updatePayload.progression_notes = data.progression_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.injury !== undefined) {
            await physio_exercises.setInjury(
              
              data.injury,
              
              { transaction }
            );
        }
        
        if (data.exercise !== undefined) {
            await physio_exercises.setExercise(
              
              data.exercise,
              
              { transaction }
            );
        }
        

        
        

        

        return physio_exercises;
    }

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

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

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


        return physio_exercises;
    }

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

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

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

        await physio_exercises.destroy({
            transaction
        });

        return physio_exercises;
    }

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

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

        if (!physio_exercises) {
            return physio_exercises;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.injury = await physio_exercises.getInjury({
            transaction
        });
        
        
        output.exercise = await physio_exercises.getExercise({
            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.injuries,
        as: 'injury',
        
        where: filter.injury ? {
          [Op.or]: [
            { id: { [Op.in]: filter.injury.split('|').map(term => Utils.uuid(term)) } },
            {
              diagnosis: {
                [Op.or]: filter.injury.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    reps: {
                    ...where.reps,
                            [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.physio_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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'physio_exercises',
                        'progression_notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

