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

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

        const strength_sets = await db.strength_sets.create(
            {
                id: data.id || undefined,
        
        set_number: data.set_number
        ||
        null
            ,
            
        reps: data.reps
        ||
        null
            ,
            
        weight: data.weight
        ||
        null
            ,
            
        weight_unit: data.weight_unit
        ||
        null
            ,
            
        rpe: data.rpe
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await strength_sets.setWorkout_session( data.workout_session || null, {
            transaction,
        });
        
        await strength_sets.setExercise( data.exercise || null, {
            transaction,
        });
        

        

        

        return strength_sets;
    }
    

    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 strength_setsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                set_number: item.set_number
            ||
            null
            ,
            
                reps: item.reps
            ||
            null
            ,
            
                weight: item.weight
            ||
            null
            ,
            
                weight_unit: item.weight_unit
            ||
            null
            ,
            
                rpe: item.rpe
            ||
            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 strength_sets = await db.strength_sets.bulkCreate(strength_setsData, { transaction });

        // For each item created, replace relation files
        

        return strength_sets;
    }

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

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


        

        const updatePayload = {};
        
        if (data.set_number !== undefined) updatePayload.set_number = data.set_number;
        
        
        if (data.reps !== undefined) updatePayload.reps = data.reps;
        
        
        if (data.weight !== undefined) updatePayload.weight = data.weight;
        
        
        if (data.weight_unit !== undefined) updatePayload.weight_unit = data.weight_unit;
        
        
        if (data.rpe !== undefined) updatePayload.rpe = data.rpe;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.workout_session !== undefined) {
            await strength_sets.setWorkout_session(
              
              data.workout_session,
              
              { transaction }
            );
        }
        
        if (data.exercise !== undefined) {
            await strength_sets.setExercise(
              
              data.exercise,
              
              { transaction }
            );
        }
        

        
        

        

        return strength_sets;
    }

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

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

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


        return strength_sets;
    }

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

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

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

        await strength_sets.destroy({
            transaction
        });

        return strength_sets;
    }

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

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

        if (!strength_sets) {
            return strength_sets;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.workout_session = await strength_sets.getWorkout_session({
            transaction
        });
        
        
        output.exercise = await strength_sets.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.workout_sessions,
        as: 'workout_session',
        
        where: filter.workout_session ? {
          [Op.or]: [
            { id: { [Op.in]: filter.workout_session.split('|').map(term => Utils.uuid(term)) } },
            {
              notes: {
                [Op.or]: filter.workout_session.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.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'strength_sets',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.weight_unit) {
                where = {
                    ...where,
                weight_unit: filter.weight_unit,
            };
            }
            


      

      



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

        const records = await db.strength_sets.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,
        }));
    }

    
};

