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

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

        const saved_list_items = await db.saved_list_items.create(
            {
                id: data.id || undefined,
        
        default_quantity_cases: data.default_quantity_cases
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await saved_list_items.setSaved_list( data.saved_list || null, {
            transaction,
        });
        
        await saved_list_items.setProduct( data.product || null, {
            transaction,
        });
        

        

        

        return saved_list_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 saved_list_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                default_quantity_cases: item.default_quantity_cases
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return saved_list_items;
    }

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

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


        

        const updatePayload = {};
        
        if (data.default_quantity_cases !== undefined) updatePayload.default_quantity_cases = data.default_quantity_cases;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.saved_list !== undefined) {
            await saved_list_items.setSaved_list(
              
              data.saved_list,
              
              { transaction }
            );
        }
        
        if (data.product !== undefined) {
            await saved_list_items.setProduct(
              
              data.product,
              
              { transaction }
            );
        }
        

        
        

        

        return saved_list_items;
    }

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

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

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


        return saved_list_items;
    }

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

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

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

        await saved_list_items.destroy({
            transaction
        });

        return saved_list_items;
    }

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

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

        if (!saved_list_items) {
            return saved_list_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.saved_list = await saved_list_items.getSaved_list({
            transaction
        });
        
        
        output.product = await saved_list_items.getProduct({
            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.saved_lists,
        as: 'saved_list',
        
        where: filter.saved_list ? {
          [Op.or]: [
            { id: { [Op.in]: filter.saved_list.split('|').map(term => Utils.uuid(term)) } },
            {
              list_name: {
                [Op.or]: filter.saved_list.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'saved_list_items',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    default_quantity_cases: {
                    ...where.default_quantity_cases,
                            [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.saved_list_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(
                        'saved_list_items',
                        'notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

