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

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

        const recipes = await db.recipes.create(
            {
                id: data.id || undefined,
        
        recipe_name: data.recipe_name
        ||
        null
            ,
            
        prep_time_minutes: data.prep_time_minutes
        ||
        null
            ,
            
        cook_time_minutes: data.cook_time_minutes
        ||
        null
            ,
            
        servings: data.servings
        ||
        null
            ,
            
        difficulty: data.difficulty
        ||
        null
            ,
            
        tags_csv: data.tags_csv
        ||
        null
            ,
            
        ingredients_text: data.ingredients_text
        ||
        null
            ,
            
        instructions_text: data.instructions_text
        ||
        null
            ,
            
        nutrition_per_serving_json: data.nutrition_per_serving_json
        ||
        null
            ,
            
        is_favourite: data.is_favourite
        ||
        false
        
            ,
            
        rating: data.rating
        ||
        null
            ,
            
        source_url: data.source_url
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.recipes.getTableName(),
                belongsToColumn: 'photo',
                belongsToId: recipes.id,
            },
            data.photo,
            options,
        );
        

        return recipes;
    }
    

    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 recipesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                recipe_name: item.recipe_name
            ||
            null
            ,
            
                prep_time_minutes: item.prep_time_minutes
            ||
            null
            ,
            
                cook_time_minutes: item.cook_time_minutes
            ||
            null
            ,
            
                servings: item.servings
            ||
            null
            ,
            
                difficulty: item.difficulty
            ||
            null
            ,
            
                tags_csv: item.tags_csv
            ||
            null
            ,
            
                ingredients_text: item.ingredients_text
            ||
            null
            ,
            
                instructions_text: item.instructions_text
            ||
            null
            ,
            
                nutrition_per_serving_json: item.nutrition_per_serving_json
            ||
            null
            ,
            
                is_favourite: item.is_favourite
            ||
            false
        
            ,
            
                rating: item.rating
            ||
            null
            ,
            
                source_url: item.source_url
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < recipes.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.recipes.getTableName(),
                    belongsToColumn: 'photo',
                    belongsToId: recipes[i].id,
                },
                data[i].photo,
                options,
            );
        }
        

        return recipes;
    }

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

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


        

        const updatePayload = {};
        
        if (data.recipe_name !== undefined) updatePayload.recipe_name = data.recipe_name;
        
        
        if (data.prep_time_minutes !== undefined) updatePayload.prep_time_minutes = data.prep_time_minutes;
        
        
        if (data.cook_time_minutes !== undefined) updatePayload.cook_time_minutes = data.cook_time_minutes;
        
        
        if (data.servings !== undefined) updatePayload.servings = data.servings;
        
        
        if (data.difficulty !== undefined) updatePayload.difficulty = data.difficulty;
        
        
        if (data.tags_csv !== undefined) updatePayload.tags_csv = data.tags_csv;
        
        
        if (data.ingredients_text !== undefined) updatePayload.ingredients_text = data.ingredients_text;
        
        
        if (data.instructions_text !== undefined) updatePayload.instructions_text = data.instructions_text;
        
        
        if (data.nutrition_per_serving_json !== undefined) updatePayload.nutrition_per_serving_json = data.nutrition_per_serving_json;
        
        
        if (data.is_favourite !== undefined) updatePayload.is_favourite = data.is_favourite;
        
        
        if (data.rating !== undefined) updatePayload.rating = data.rating;
        
        
        if (data.source_url !== undefined) updatePayload.source_url = data.source_url;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.recipes.getTableName(),
                belongsToColumn: 'photo',
                belongsToId: recipes.id,
            },
            data.photo,
            options,
        );
        

        return recipes;
    }

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

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

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


        return recipes;
    }

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

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

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

        await recipes.destroy({
            transaction
        });

        return recipes;
    }

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

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

        if (!recipes) {
            return recipes;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.meal_items_recipe = await recipes.getMeal_items_recipe({
            transaction
        });
        
        
        
        
        output.meal_plan_items_recipe = await recipes.getMeal_plan_items_recipe({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await recipes.getUser({
            transaction
        });
        
        
        output.photo = await recipes.getPhoto({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },



      {
        model: db.file,
        as: 'photo',
      },

    ];

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

            
            if (filter.recipe_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'recipes',
                        'recipe_name',
                        filter.recipe_name,
                    ),
                };
            }
            
            if (filter.tags_csv) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'recipes',
                        'tags_csv',
                        filter.tags_csv,
                    ),
                };
            }
            
            if (filter.ingredients_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'recipes',
                        'ingredients_text',
                        filter.ingredients_text,
                    ),
                };
            }
            
            if (filter.instructions_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'recipes',
                        'instructions_text',
                        filter.instructions_text,
                    ),
                };
            }
            
            if (filter.nutrition_per_serving_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'recipes',
                        'nutrition_per_serving_json',
                        filter.nutrition_per_serving_json,
                    ),
                };
            }
            
            if (filter.source_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'recipes',
                        'source_url',
                        filter.source_url,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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


      



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

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

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

    
};

