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

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

        const foods = await db.foods.create(
            {
                id: data.id || undefined,
        
        food_name: data.food_name
        ||
        null
            ,
            
        brand: data.brand
        ||
        null
            ,
            
        barcode: data.barcode
        ||
        null
            ,
            
        serving_size_g: data.serving_size_g
        ||
        null
            ,
            
        calories: data.calories
        ||
        null
            ,
            
        protein_g: data.protein_g
        ||
        null
            ,
            
        carbs_g: data.carbs_g
        ||
        null
            ,
            
        sugars_g: data.sugars_g
        ||
        null
            ,
            
        fat_g: data.fat_g
        ||
        null
            ,
            
        saturated_fat_g: data.saturated_fat_g
        ||
        null
            ,
            
        fibre_g: data.fibre_g
        ||
        null
            ,
            
        sodium_mg: data.sodium_mg
        ||
        null
            ,
            
        micronutrients_json: data.micronutrients_json
        ||
        null
            ,
            
        fodmap_tag: data.fodmap_tag
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return foods;
    }
    

    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 foodsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                food_name: item.food_name
            ||
            null
            ,
            
                brand: item.brand
            ||
            null
            ,
            
                barcode: item.barcode
            ||
            null
            ,
            
                serving_size_g: item.serving_size_g
            ||
            null
            ,
            
                calories: item.calories
            ||
            null
            ,
            
                protein_g: item.protein_g
            ||
            null
            ,
            
                carbs_g: item.carbs_g
            ||
            null
            ,
            
                sugars_g: item.sugars_g
            ||
            null
            ,
            
                fat_g: item.fat_g
            ||
            null
            ,
            
                saturated_fat_g: item.saturated_fat_g
            ||
            null
            ,
            
                fibre_g: item.fibre_g
            ||
            null
            ,
            
                sodium_mg: item.sodium_mg
            ||
            null
            ,
            
                micronutrients_json: item.micronutrients_json
            ||
            null
            ,
            
                fodmap_tag: item.fodmap_tag
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return foods;
    }

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

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


        

        const updatePayload = {};
        
        if (data.food_name !== undefined) updatePayload.food_name = data.food_name;
        
        
        if (data.brand !== undefined) updatePayload.brand = data.brand;
        
        
        if (data.barcode !== undefined) updatePayload.barcode = data.barcode;
        
        
        if (data.serving_size_g !== undefined) updatePayload.serving_size_g = data.serving_size_g;
        
        
        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.sugars_g !== undefined) updatePayload.sugars_g = data.sugars_g;
        
        
        if (data.fat_g !== undefined) updatePayload.fat_g = data.fat_g;
        
        
        if (data.saturated_fat_g !== undefined) updatePayload.saturated_fat_g = data.saturated_fat_g;
        
        
        if (data.fibre_g !== undefined) updatePayload.fibre_g = data.fibre_g;
        
        
        if (data.sodium_mg !== undefined) updatePayload.sodium_mg = data.sodium_mg;
        
        
        if (data.micronutrients_json !== undefined) updatePayload.micronutrients_json = data.micronutrients_json;
        
        
        if (data.fodmap_tag !== undefined) updatePayload.fodmap_tag = data.fodmap_tag;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return foods;
    }

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

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

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


        return foods;
    }

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

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

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

        await foods.destroy({
            transaction
        });

        return foods;
    }

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

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

        if (!foods) {
            return foods;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.meal_items_food = await foods.getMeal_items_food({
            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 = [



    ];

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

            
            if (filter.food_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'foods',
                        'food_name',
                        filter.food_name,
                    ),
                };
            }
            
            if (filter.brand) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'foods',
                        'brand',
                        filter.brand,
                    ),
                };
            }
            
            if (filter.barcode) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'foods',
                        'barcode',
                        filter.barcode,
                    ),
                };
            }
            
            if (filter.micronutrients_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'foods',
                        'micronutrients_json',
                        filter.micronutrients_json,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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




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

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

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

    
};

