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

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

        const shelf_slots = await db.shelf_slots.create(
            {
                id: data.id || undefined,
        
        facings: data.facings
        ||
        null
            ,
            
        max_quantity: data.max_quantity
        ||
        null
            ,
            
        current_quantity: data.current_quantity
        ||
        null
            ,
            
        slot_index: data.slot_index
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await shelf_slots.setShelf( data.shelf || null, {
            transaction,
        });
        
        await shelf_slots.setStore_product( data.store_product || null, {
            transaction,
        });
        

        

        

        return shelf_slots;
    }
    

    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 shelf_slotsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                facings: item.facings
            ||
            null
            ,
            
                max_quantity: item.max_quantity
            ||
            null
            ,
            
                current_quantity: item.current_quantity
            ||
            null
            ,
            
                slot_index: item.slot_index
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return shelf_slots;
    }

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

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


        

        const updatePayload = {};
        
        if (data.facings !== undefined) updatePayload.facings = data.facings;
        
        
        if (data.max_quantity !== undefined) updatePayload.max_quantity = data.max_quantity;
        
        
        if (data.current_quantity !== undefined) updatePayload.current_quantity = data.current_quantity;
        
        
        if (data.slot_index !== undefined) updatePayload.slot_index = data.slot_index;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.shelf !== undefined) {
            await shelf_slots.setShelf(
              
              data.shelf,
              
              { transaction }
            );
        }
        
        if (data.store_product !== undefined) {
            await shelf_slots.setStore_product(
              
              data.store_product,
              
              { transaction }
            );
        }
        

        
        

        

        return shelf_slots;
    }

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

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

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


        return shelf_slots;
    }

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

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

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

        await shelf_slots.destroy({
            transaction
        });

        return shelf_slots;
    }

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

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

        if (!shelf_slots) {
            return shelf_slots;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.shelf = await shelf_slots.getShelf({
            transaction
        });
        
        
        output.store_product = await shelf_slots.getStore_product({
            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.shelves,
        as: 'shelf',
        
        where: filter.shelf ? {
          [Op.or]: [
            { id: { [Op.in]: filter.shelf.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.shelf.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            

            
            

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

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

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

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

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

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

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

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

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

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

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

    
};

