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

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

        const workout_exercises = await db.workout_exercises.create(
            {
                id: data.id || undefined,
        
        sort_order: data.sort_order
        ||
        null
            ,
            
        sets: data.sets
        ||
        null
            ,
            
        reps: data.reps
        ||
        null
            ,
            
        rest_seconds: data.rest_seconds
        ||
        null
            ,
            
        beginner_modifications: data.beginner_modifications
        ||
        null
            ,
            
        advanced_progressions: data.advanced_progressions
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await workout_exercises.setWorkout( data.workout || null, {
            transaction,
        });
        
        await workout_exercises.setExercise( data.exercise || null, {
            transaction,
        });
        

        

        

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

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

        // For each item created, replace relation files
        

        return workout_exercises;
    }

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

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


        

        const updatePayload = {};
        
        if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
        
        
        if (data.sets !== undefined) updatePayload.sets = data.sets;
        
        
        if (data.reps !== undefined) updatePayload.reps = data.reps;
        
        
        if (data.rest_seconds !== undefined) updatePayload.rest_seconds = data.rest_seconds;
        
        
        if (data.beginner_modifications !== undefined) updatePayload.beginner_modifications = data.beginner_modifications;
        
        
        if (data.advanced_progressions !== undefined) updatePayload.advanced_progressions = data.advanced_progressions;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.workout !== undefined) {
            await workout_exercises.setWorkout(
              
              data.workout,
              
              { transaction }
            );
        }
        
        if (data.exercise !== undefined) {
            await workout_exercises.setExercise(
              
              data.exercise,
              
              { transaction }
            );
        }
        

        
        

        

        return workout_exercises;
    }

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

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

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


        return workout_exercises;
    }

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

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

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

        await workout_exercises.destroy({
            transaction
        });

        return workout_exercises;
    }

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

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

        if (!workout_exercises) {
            return workout_exercises;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.workout = await workout_exercises.getWorkout({
            transaction
        });
        
        
        output.exercise = await workout_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.workouts,
        as: 'workout',
        
        where: filter.workout ? {
          [Op.or]: [
            { id: { [Op.in]: filter.workout.split('|').map(term => Utils.uuid(term)) } },
            {
              workout_name: {
                [Op.or]: filter.workout.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.beginner_modifications) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'workout_exercises',
                        'beginner_modifications',
                        filter.beginner_modifications,
                    ),
                };
            }
            
            if (filter.advanced_progressions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'workout_exercises',
                        'advanced_progressions',
                        filter.advanced_progressions,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    sort_order: {
                    ...where.sort_order,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.rest_secondsRange) {
                const [start, end] = filter.rest_secondsRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    rest_seconds: {
                    ...where.rest_seconds,
                            [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.workout_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(
                        'workout_exercises',
                        'beginner_modifications',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

