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

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

        const inventory_balances = await db.inventory_balances.create(
            {
                id: data.id || undefined,
        
        quantity_on_hand: data.quantity_on_hand
        ||
        null
            ,
            
        quantity_allocated: data.quantity_allocated
        ||
        null
            ,
            
        quantity_available: data.quantity_available
        ||
        null
            ,
            
        last_counted_at: data.last_counted_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await inventory_balances.setItem( data.item || null, {
            transaction,
        });
        
        await inventory_balances.setLocation( data.location || null, {
            transaction,
        });
        
        await inventory_balances.setLot( data.lot || null, {
            transaction,
        });
        

        

        

        return inventory_balances;
    }
    

    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 inventory_balancesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                quantity_on_hand: item.quantity_on_hand
            ||
            null
            ,
            
                quantity_allocated: item.quantity_allocated
            ||
            null
            ,
            
                quantity_available: item.quantity_available
            ||
            null
            ,
            
                last_counted_at: item.last_counted_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return inventory_balances;
    }

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

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


        

        const updatePayload = {};
        
        if (data.quantity_on_hand !== undefined) updatePayload.quantity_on_hand = data.quantity_on_hand;
        
        
        if (data.quantity_allocated !== undefined) updatePayload.quantity_allocated = data.quantity_allocated;
        
        
        if (data.quantity_available !== undefined) updatePayload.quantity_available = data.quantity_available;
        
        
        if (data.last_counted_at !== undefined) updatePayload.last_counted_at = data.last_counted_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.item !== undefined) {
            await inventory_balances.setItem(
              
              data.item,
              
              { transaction }
            );
        }
        
        if (data.location !== undefined) {
            await inventory_balances.setLocation(
              
              data.location,
              
              { transaction }
            );
        }
        
        if (data.lot !== undefined) {
            await inventory_balances.setLot(
              
              data.lot,
              
              { transaction }
            );
        }
        

        
        

        

        return inventory_balances;
    }

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

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

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


        return inventory_balances;
    }

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

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

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

        await inventory_balances.destroy({
            transaction
        });

        return inventory_balances;
    }

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

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

        if (!inventory_balances) {
            return inventory_balances;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.item = await inventory_balances.getItem({
            transaction
        });
        
        
        output.location = await inventory_balances.getLocation({
            transaction
        });
        
        
        output.lot = await inventory_balances.getLot({
            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.items,
        as: 'item',
        
        where: filter.item ? {
          [Op.or]: [
            { id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.item.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}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            

            
            

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

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

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

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

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

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

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

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

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

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

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

    
};

