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

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

        const restaurant_meals = await db.restaurant_meals.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        quantity_received: data.quantity_received
        ||
        null
            ,
            
        quantity_kg: data.quantity_kg
        ||
        null
            ,
            
        shortage: data.shortage
        ||
        null
            ,
            
        estimated_cost: data.estimated_cost
        ||
        null
            ,
            
        distributed_count: data.distributed_count
        ||
        null
            ,
            
        drinks_count: data.drinks_count
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return restaurant_meals;
    }
    

    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 restaurant_mealsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                quantity_received: item.quantity_received
            ||
            null
            ,
            
                quantity_kg: item.quantity_kg
            ||
            null
            ,
            
                shortage: item.shortage
            ||
            null
            ,
            
                estimated_cost: item.estimated_cost
            ||
            null
            ,
            
                distributed_count: item.distributed_count
            ||
            null
            ,
            
                drinks_count: item.drinks_count
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return restaurant_meals;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.quantity_received !== undefined) updatePayload.quantity_received = data.quantity_received;
        
        
        if (data.quantity_kg !== undefined) updatePayload.quantity_kg = data.quantity_kg;
        
        
        if (data.shortage !== undefined) updatePayload.shortage = data.shortage;
        
        
        if (data.estimated_cost !== undefined) updatePayload.estimated_cost = data.estimated_cost;
        
        
        if (data.distributed_count !== undefined) updatePayload.distributed_count = data.distributed_count;
        
        
        if (data.drinks_count !== undefined) updatePayload.drinks_count = data.drinks_count;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return restaurant_meals;
    }

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

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

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


        return restaurant_meals;
    }

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

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

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

        await restaurant_meals.destroy({
            transaction
        });

        return restaurant_meals;
    }

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

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

        if (!restaurant_meals) {
            return restaurant_meals;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        

        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.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'restaurant_meals',
                        'name',
                        filter.name,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            




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

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

    
};

