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

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

        const meal_plan_items = await db.meal_plan_items.create(
            {
                id: data.id || undefined,
        
        planned_for: data.planned_for
        ||
        null
            ,
            
        meal_type: data.meal_type
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await meal_plan_items.setMeal_plan( data.meal_plan || null, {
            transaction,
        });
        
        await meal_plan_items.setRecipe( data.recipe || null, {
            transaction,
        });
        

        

        

        return meal_plan_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_plan_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                planned_for: item.planned_for
            ||
            null
            ,
            
                meal_type: item.meal_type
            ||
            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 meal_plan_items = await db.meal_plan_items.bulkCreate(meal_plan_itemsData, { transaction });

        // For each item created, replace relation files
        

        return meal_plan_items;
    }

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

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


        

        const updatePayload = {};
        
        if (data.planned_for !== undefined) updatePayload.planned_for = data.planned_for;
        
        
        if (data.meal_type !== undefined) updatePayload.meal_type = data.meal_type;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.meal_plan !== undefined) {
            await meal_plan_items.setMeal_plan(
              
              data.meal_plan,
              
              { transaction }
            );
        }
        
        if (data.recipe !== undefined) {
            await meal_plan_items.setRecipe(
              
              data.recipe,
              
              { transaction }
            );
        }
        

        
        

        

        return meal_plan_items;
    }

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

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

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


        return meal_plan_items;
    }

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

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

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

        await meal_plan_items.destroy({
            transaction
        });

        return meal_plan_items;
    }

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

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

        if (!meal_plan_items) {
            return meal_plan_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.meal_plan = await meal_plan_items.getMeal_plan({
            transaction
        });
        
        
        output.recipe = await meal_plan_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.meal_plans,
        as: 'meal_plan',
        
        where: filter.meal_plan ? {
          [Op.or]: [
            { id: { [Op.in]: filter.meal_plan.split('|').map(term => Utils.uuid(term)) } },
            {
              dietary_restrictions: {
                [Op.or]: filter.meal_plan.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.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'meal_plan_items',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

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

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

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

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

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

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


      

      



            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_plan_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_plan_items',
                        'notes',
                        query,
                    ),
                ],
            };
        }

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

    
};

