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

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

        const workouts = await db.workouts.create(
            {
                id: data.id || undefined,
        
        workout_name: data.workout_name
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        workout_type: data.workout_type
        ||
        null
            ,
            
        goal_focus: data.goal_focus
        ||
        null
            ,
            
        difficulty: data.difficulty
        ||
        null
            ,
            
        equipment_needed: data.equipment_needed
        ||
        null
            ,
            
        duration_minutes: data.duration_minutes
        ||
        null
            ,
            
        estimated_calories: data.estimated_calories
        ||
        null
            ,
            
        average_rating: data.average_rating
        ||
        null
            ,
            
        warmup_notes: data.warmup_notes
        ||
        null
            ,
            
        cooldown_notes: data.cooldown_notes
        ||
        null
            ,
            
        safety_notes: data.safety_notes
        ||
        null
            ,
            
        video_url: data.video_url
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.workouts.getTableName(),
                belongsToColumn: 'cover_image',
                belongsToId: workouts.id,
            },
            data.cover_image,
            options,
        );
        

        return workouts;
    }
    

    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 workoutsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                workout_name: item.workout_name
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                workout_type: item.workout_type
            ||
            null
            ,
            
                goal_focus: item.goal_focus
            ||
            null
            ,
            
                difficulty: item.difficulty
            ||
            null
            ,
            
                equipment_needed: item.equipment_needed
            ||
            null
            ,
            
                duration_minutes: item.duration_minutes
            ||
            null
            ,
            
                estimated_calories: item.estimated_calories
            ||
            null
            ,
            
                average_rating: item.average_rating
            ||
            null
            ,
            
                warmup_notes: item.warmup_notes
            ||
            null
            ,
            
                cooldown_notes: item.cooldown_notes
            ||
            null
            ,
            
                safety_notes: item.safety_notes
            ||
            null
            ,
            
                video_url: item.video_url
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < workouts.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.workouts.getTableName(),
                    belongsToColumn: 'cover_image',
                    belongsToId: workouts[i].id,
                },
                data[i].cover_image,
                options,
            );
        }
        

        return workouts;
    }

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

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


        

        const updatePayload = {};
        
        if (data.workout_name !== undefined) updatePayload.workout_name = data.workout_name;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.workout_type !== undefined) updatePayload.workout_type = data.workout_type;
        
        
        if (data.goal_focus !== undefined) updatePayload.goal_focus = data.goal_focus;
        
        
        if (data.difficulty !== undefined) updatePayload.difficulty = data.difficulty;
        
        
        if (data.equipment_needed !== undefined) updatePayload.equipment_needed = data.equipment_needed;
        
        
        if (data.duration_minutes !== undefined) updatePayload.duration_minutes = data.duration_minutes;
        
        
        if (data.estimated_calories !== undefined) updatePayload.estimated_calories = data.estimated_calories;
        
        
        if (data.average_rating !== undefined) updatePayload.average_rating = data.average_rating;
        
        
        if (data.warmup_notes !== undefined) updatePayload.warmup_notes = data.warmup_notes;
        
        
        if (data.cooldown_notes !== undefined) updatePayload.cooldown_notes = data.cooldown_notes;
        
        
        if (data.safety_notes !== undefined) updatePayload.safety_notes = data.safety_notes;
        
        
        if (data.video_url !== undefined) updatePayload.video_url = data.video_url;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.workouts.getTableName(),
                belongsToColumn: 'cover_image',
                belongsToId: workouts.id,
            },
            data.cover_image,
            options,
        );
        

        return workouts;
    }

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

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

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


        return workouts;
    }

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

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

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

        await workouts.destroy({
            transaction
        });

        return workouts;
    }

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

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

        if (!workouts) {
            return workouts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.workout_exercises_workout = await workouts.getWorkout_exercises_workout({
            transaction
        });
        
        
        output.workout_schedules_workout = await workouts.getWorkout_schedules_workout({
            transaction
        });
        
        
        
        output.workout_sessions_workout = await workouts.getWorkout_sessions_workout({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.cover_image = await workouts.getCover_image({
            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.file,
        as: 'cover_image',
      },

    ];

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

            
            if (filter.workout_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'workouts',
                        'workout_name',
                        filter.workout_name,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'workouts',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.warmup_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'workouts',
                        'warmup_notes',
                        filter.warmup_notes,
                    ),
                };
            }
            
            if (filter.cooldown_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'workouts',
                        'cooldown_notes',
                        filter.cooldown_notes,
                    ),
                };
            }
            
            if (filter.safety_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'workouts',
                        'safety_notes',
                        filter.safety_notes,
                    ),
                };
            }
            
            if (filter.video_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'workouts',
                        'video_url',
                        filter.video_url,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.workout_type) {
                where = {
                    ...where,
                workout_type: filter.workout_type,
            };
            }
            
            if (filter.goal_focus) {
                where = {
                    ...where,
                goal_focus: filter.goal_focus,
            };
            }
            
            if (filter.difficulty) {
                where = {
                    ...where,
                difficulty: filter.difficulty,
            };
            }
            
            if (filter.equipment_needed) {
                where = {
                    ...where,
                equipment_needed: filter.equipment_needed,
            };
            }
            




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

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

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

    
};

