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

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

        const nutrition_targets = await db.nutrition_targets.create(
            {
                id: data.id || undefined,
        
        effective_from: data.effective_from
        ||
        null
            ,
            
        effective_to: data.effective_to
        ||
        null
            ,
            
        bmr: data.bmr
        ||
        null
            ,
            
        tdee: data.tdee
        ||
        null
            ,
            
        goal_mode: data.goal_mode
        ||
        null
            ,
            
        calorie_target: data.calorie_target
        ||
        null
            ,
            
        protein_target_g: data.protein_target_g
        ||
        null
            ,
            
        carb_target_g: data.carb_target_g
        ||
        null
            ,
            
        fat_target_g: data.fat_target_g
        ||
        null
            ,
            
        macro_preset_name: data.macro_preset_name
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return nutrition_targets;
    }
    

    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 nutrition_targetsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                effective_from: item.effective_from
            ||
            null
            ,
            
                effective_to: item.effective_to
            ||
            null
            ,
            
                bmr: item.bmr
            ||
            null
            ,
            
                tdee: item.tdee
            ||
            null
            ,
            
                goal_mode: item.goal_mode
            ||
            null
            ,
            
                calorie_target: item.calorie_target
            ||
            null
            ,
            
                protein_target_g: item.protein_target_g
            ||
            null
            ,
            
                carb_target_g: item.carb_target_g
            ||
            null
            ,
            
                fat_target_g: item.fat_target_g
            ||
            null
            ,
            
                macro_preset_name: item.macro_preset_name
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return nutrition_targets;
    }

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

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


        

        const updatePayload = {};
        
        if (data.effective_from !== undefined) updatePayload.effective_from = data.effective_from;
        
        
        if (data.effective_to !== undefined) updatePayload.effective_to = data.effective_to;
        
        
        if (data.bmr !== undefined) updatePayload.bmr = data.bmr;
        
        
        if (data.tdee !== undefined) updatePayload.tdee = data.tdee;
        
        
        if (data.goal_mode !== undefined) updatePayload.goal_mode = data.goal_mode;
        
        
        if (data.calorie_target !== undefined) updatePayload.calorie_target = data.calorie_target;
        
        
        if (data.protein_target_g !== undefined) updatePayload.protein_target_g = data.protein_target_g;
        
        
        if (data.carb_target_g !== undefined) updatePayload.carb_target_g = data.carb_target_g;
        
        
        if (data.fat_target_g !== undefined) updatePayload.fat_target_g = data.fat_target_g;
        
        
        if (data.macro_preset_name !== undefined) updatePayload.macro_preset_name = data.macro_preset_name;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return nutrition_targets;
    }

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

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

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


        return nutrition_targets;
    }

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

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

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

        await nutrition_targets.destroy({
            transaction
        });

        return nutrition_targets;
    }

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

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

        if (!nutrition_targets) {
            return nutrition_targets;
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


      



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

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

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

    
};

