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

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

        const meal_items = await db.meal_items.create(
            {
                id: data.id || undefined,
        
        quantity: data.quantity
        ||
        null
            ,
            
        quantity_unit: data.quantity_unit
        ||
        null
            ,
            
        calories: data.calories
        ||
        null
            ,
            
        protein_g: data.protein_g
        ||
        null
            ,
            
        carbs_g: data.carbs_g
        ||
        null
            ,
            
        fat_g: data.fat_g
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await meal_items.setMeal( data.meal || null, {
            transaction,
        });
        
        await meal_items.setFood( data.food || null, {
            transaction,
        });
        
        await meal_items.setRecipe( data.recipe || null, {
            transaction,
        });
        

        

        

        return meal_items;
    }
    

    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 meal_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                quantity: item.quantity
            ||
            null
            ,
            
                quantity_unit: item.quantity_unit
            ||
            null
            ,
            
                calories: item.calories
            ||
            null
            ,
            
                protein_g: item.protein_g
            ||
            null
            ,
            
                carbs_g: item.carbs_g
            ||
            null
            ,
            
                fat_g: item.fat_g
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return meal_items;
    }

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

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


        

        const updatePayload = {};
        
        if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
        
        
        if (data.quantity_unit !== undefined) updatePayload.quantity_unit = data.quantity_unit;
        
        
        if (data.calories !== undefined) updatePayload.calories = data.calories;
        
        
        if (data.protein_g !== undefined) updatePayload.protein_g = data.protein_g;
        
        
        if (data.carbs_g !== undefined) updatePayload.carbs_g = data.carbs_g;
        
        
        if (data.fat_g !== undefined) updatePayload.fat_g = data.fat_g;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.meal !== undefined) {
            await meal_items.setMeal(
              
              data.meal,
              
              { transaction }
            );
        }
        
        if (data.food !== undefined) {
            await meal_items.setFood(
              
              data.food,
              
              { transaction }
            );
        }
        
        if (data.recipe !== undefined) {
            await meal_items.setRecipe(
              
              data.recipe,
              
              { transaction }
            );
        }
        

        
        

        

        return meal_items;
    }

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

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

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


        return meal_items;
    }

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

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

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

        await meal_items.destroy({
            transaction
        });

        return meal_items;
    }

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

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

        if (!meal_items) {
            return meal_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.meal = await meal_items.getMeal({
            transaction
        });
        
        
        output.food = await meal_items.getFood({
            transaction
        });
        
        
        output.recipe = await meal_items.getRecipe({
            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.meals,
        as: 'meal',
        
        where: filter.meal ? {
          [Op.or]: [
            { id: { [Op.in]: filter.meal.split('|').map(term => Utils.uuid(term)) } },
            {
              meal_title: {
                [Op.or]: filter.meal.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.foods,
        as: 'food',
        
        where: filter.food ? {
          [Op.or]: [
            { id: { [Op.in]: filter.food.split('|').map(term => Utils.uuid(term)) } },
            {
              food_name: {
                [Op.or]: filter.food.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.recipes,
        as: 'recipe',
        
        where: filter.recipe ? {
          [Op.or]: [
            { id: { [Op.in]: filter.recipe.split('|').map(term => Utils.uuid(term)) } },
            {
              recipe_name: {
                [Op.or]: filter.recipe.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

    
};

