
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,
        
        on_hand_quantity: data.on_hand_quantity
        ||
        null
            ,
            
        allocated_quantity: data.allocated_quantity
        ||
        null
            ,
            
        available_quantity: data.available_quantity
        ||
        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,
        });
        
        await inventory_balances.setSerial( data.serial || 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,
                
                on_hand_quantity: item.on_hand_quantity
            ||
            null
            ,
            
                allocated_quantity: item.allocated_quantity
            ||
            null
            ,
            
                available_quantity: item.available_quantity
            ||
            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.on_hand_quantity !== undefined) updatePayload.on_hand_quantity = data.on_hand_quantity;
        
        
        if (data.allocated_quantity !== undefined) updatePayload.allocated_quantity = data.allocated_quantity;
        
        
        if (data.available_quantity !== undefined) updatePayload.available_quantity = data.available_quantity;
        
        
        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 }
            );
        }
        
        if (data.serial !== undefined) {
            await inventory_balances.setSerial(
              
              data.serial,
              
              { 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
        });
        
        
        output.serial = await inventory_balances.getSerial({
            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)) } },
            {
              item_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)) } },
            {
              location_name: {
                [Op.or]: filter.location.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.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}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            

            
            

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

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

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

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

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

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

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

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

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

    
};

