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

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

        const menu_items = await db.menu_items.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        item_type: data.item_type
        ||
        null
            ,
            
        price: data.price
        ||
        null
            ,
            
        is_available: data.is_available
        ||
        false
        
            ,
            
        prep_time_minutes: data.prep_time_minutes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await menu_items.setRestaurant( data.restaurant || null, {
            transaction,
        });
        
        await menu_items.setMenu_category( data.menu_category || null, {
            transaction,
        });
        

        

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

        return menu_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 menu_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                item_type: item.item_type
            ||
            null
            ,
            
                price: item.price
            ||
            null
            ,
            
                is_available: item.is_available
            ||
            false
        
            ,
            
                prep_time_minutes: item.prep_time_minutes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return menu_items;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.item_type !== undefined) updatePayload.item_type = data.item_type;
        
        
        if (data.price !== undefined) updatePayload.price = data.price;
        
        
        if (data.is_available !== undefined) updatePayload.is_available = data.is_available;
        
        
        if (data.prep_time_minutes !== undefined) updatePayload.prep_time_minutes = data.prep_time_minutes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.restaurant !== undefined) {
            await menu_items.setRestaurant(
              
              data.restaurant,
              
              { transaction }
            );
        }
        
        if (data.menu_category !== undefined) {
            await menu_items.setMenu_category(
              
              data.menu_category,
              
              { transaction }
            );
        }
        

        
        

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

        return menu_items;
    }

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

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

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


        return menu_items;
    }

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

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

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

        await menu_items.destroy({
            transaction
        });

        return menu_items;
    }

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

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

        if (!menu_items) {
            return menu_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.order_items_menu_item = await menu_items.getOrder_items_menu_item({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.restaurant = await menu_items.getRestaurant({
            transaction
        });
        
        
        output.menu_category = await menu_items.getMenu_category({
            transaction
        });
        
        
        output.images = await menu_items.getImages({
            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.restaurants,
        as: 'restaurant',
        
        where: filter.restaurant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.restaurant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.restaurant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'menu_items',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'menu_items',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    price: {
                    ...where.price,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

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


      

      



            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.menu_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(
                        'menu_items',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

