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

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

        const meal_plans = await db.meal_plans.create(
            {
                id: data.id || undefined,
        
        week_start_date: data.week_start_date
        ||
        null
            ,
            
        people_count: data.people_count
        ||
        null
            ,
            
        cooking_skill_level: data.cooking_skill_level
        ||
        null
            ,
            
        dietary_restrictions: data.dietary_restrictions
        ||
        null
            ,
            
        cuisine_preferences: data.cuisine_preferences
        ||
        null
            ,
            
        prep_time_minutes_per_day: data.prep_time_minutes_per_day
        ||
        null
            ,
            
        target_calories_per_day: data.target_calories_per_day
        ||
        null
            ,
            
        ai_plan_json: data.ai_plan_json
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return meal_plans;
    }
    

    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_plansData = data.map((item, index) => ({
                id: item.id || undefined,
                
                week_start_date: item.week_start_date
            ||
            null
            ,
            
                people_count: item.people_count
            ||
            null
            ,
            
                cooking_skill_level: item.cooking_skill_level
            ||
            null
            ,
            
                dietary_restrictions: item.dietary_restrictions
            ||
            null
            ,
            
                cuisine_preferences: item.cuisine_preferences
            ||
            null
            ,
            
                prep_time_minutes_per_day: item.prep_time_minutes_per_day
            ||
            null
            ,
            
                target_calories_per_day: item.target_calories_per_day
            ||
            null
            ,
            
                ai_plan_json: item.ai_plan_json
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return meal_plans;
    }

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

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


        

        const updatePayload = {};
        
        if (data.week_start_date !== undefined) updatePayload.week_start_date = data.week_start_date;
        
        
        if (data.people_count !== undefined) updatePayload.people_count = data.people_count;
        
        
        if (data.cooking_skill_level !== undefined) updatePayload.cooking_skill_level = data.cooking_skill_level;
        
        
        if (data.dietary_restrictions !== undefined) updatePayload.dietary_restrictions = data.dietary_restrictions;
        
        
        if (data.cuisine_preferences !== undefined) updatePayload.cuisine_preferences = data.cuisine_preferences;
        
        
        if (data.prep_time_minutes_per_day !== undefined) updatePayload.prep_time_minutes_per_day = data.prep_time_minutes_per_day;
        
        
        if (data.target_calories_per_day !== undefined) updatePayload.target_calories_per_day = data.target_calories_per_day;
        
        
        if (data.ai_plan_json !== undefined) updatePayload.ai_plan_json = data.ai_plan_json;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return meal_plans;
    }

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

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

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


        return meal_plans;
    }

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

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

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

        await meal_plans.destroy({
            transaction
        });

        return meal_plans;
    }

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

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

        if (!meal_plans) {
            return meal_plans;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.meal_plan_items_meal_plan = await meal_plans.getMeal_plan_items_meal_plan({
            transaction
        });
        
        
        output.grocery_lists_meal_plan = await meal_plans.getGrocery_lists_meal_plan({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await meal_plans.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.dietary_restrictions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'meal_plans',
                        'dietary_restrictions',
                        filter.dietary_restrictions,
                    ),
                };
            }
            
            if (filter.cuisine_preferences) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'meal_plans',
                        'cuisine_preferences',
                        filter.cuisine_preferences,
                    ),
                };
            }
            
            if (filter.ai_plan_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'meal_plans',
                        'ai_plan_json',
                        filter.ai_plan_json,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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


      



            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_plans.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_plans',
                        'dietary_restrictions',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

