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

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

        const shelves = await db.shelves.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        shelf_type: data.shelf_type
        ||
        null
            ,
            
        capacity_units: data.capacity_units
        ||
        null
            ,
            
        is_customer_accessible: data.is_customer_accessible
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await shelves.setStore( data.store || null, {
            transaction,
        });
        
        await shelves.setLocation( data.location || null, {
            transaction,
        });
        

        

        

        return shelves;
    }
    

    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 shelvesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                shelf_type: item.shelf_type
            ||
            null
            ,
            
                capacity_units: item.capacity_units
            ||
            null
            ,
            
                is_customer_accessible: item.is_customer_accessible
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return shelves;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.shelf_type !== undefined) updatePayload.shelf_type = data.shelf_type;
        
        
        if (data.capacity_units !== undefined) updatePayload.capacity_units = data.capacity_units;
        
        
        if (data.is_customer_accessible !== undefined) updatePayload.is_customer_accessible = data.is_customer_accessible;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.store !== undefined) {
            await shelves.setStore(
              
              data.store,
              
              { transaction }
            );
        }
        
        if (data.location !== undefined) {
            await shelves.setLocation(
              
              data.location,
              
              { transaction }
            );
        }
        

        
        

        

        return shelves;
    }

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

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

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


        return shelves;
    }

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

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

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

        await shelves.destroy({
            transaction
        });

        return shelves;
    }

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

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

        if (!shelves) {
            return shelves;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.shelf_slots_shelf = await shelves.getShelf_slots_shelf({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.store = await shelves.getStore({
            transaction
        });
        
        
        output.location = await shelves.getLocation({
            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.market_stores,
        as: 'store',
        
        where: filter.store ? {
          [Op.or]: [
            { id: { [Op.in]: filter.store.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.store.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

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

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

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

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

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


      

      



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

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

    
};

