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

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

        const grocery_items = await db.grocery_items.create(
            {
                id: data.id || undefined,
        
        item_name: data.item_name
        ||
        null
            ,
            
        category: data.category
        ||
        null
            ,
            
        quantity: data.quantity
        ||
        null
            ,
            
        unit: data.unit
        ||
        null
            ,
            
        is_purchased: data.is_purchased
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await grocery_items.setGrocery_list( data.grocery_list || null, {
            transaction,
        });
        

        

        

        return grocery_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 grocery_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                item_name: item.item_name
            ||
            null
            ,
            
                category: item.category
            ||
            null
            ,
            
                quantity: item.quantity
            ||
            null
            ,
            
                unit: item.unit
            ||
            null
            ,
            
                is_purchased: item.is_purchased
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return grocery_items;
    }

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

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


        

        const updatePayload = {};
        
        if (data.item_name !== undefined) updatePayload.item_name = data.item_name;
        
        
        if (data.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
        
        
        if (data.unit !== undefined) updatePayload.unit = data.unit;
        
        
        if (data.is_purchased !== undefined) updatePayload.is_purchased = data.is_purchased;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.grocery_list !== undefined) {
            await grocery_items.setGrocery_list(
              
              data.grocery_list,
              
              { transaction }
            );
        }
        

        
        

        

        return grocery_items;
    }

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

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

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


        return grocery_items;
    }

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

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

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

        await grocery_items.destroy({
            transaction
        });

        return grocery_items;
    }

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

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

        if (!grocery_items) {
            return grocery_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.grocery_list = await grocery_items.getGrocery_list({
            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.grocery_lists,
        as: 'grocery_list',
        
        where: filter.grocery_list ? {
          [Op.or]: [
            { id: { [Op.in]: filter.grocery_list.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.grocery_list.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.item_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'grocery_items',
                        'item_name',
                        filter.item_name,
                    ),
                };
            }
            
            if (filter.category) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'grocery_items',
                        'category',
                        filter.category,
                    ),
                };
            }
            
            if (filter.unit) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'grocery_items',
                        'unit',
                        filter.unit,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      



            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.grocery_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(
                        'grocery_items',
                        'item_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

