
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_qty: data.on_hand_qty
        ||
        null
            ,
            
        allocated_qty: data.allocated_qty
        ||
        null
            ,
            
        available_qty: data.available_qty
        ||
        null
            ,
            
        uom: data.uom
        ||
        null
            ,
            
        as_of: data.as_of
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await inventory_balances.setMaterial( data.material || null, {
            transaction,
        });
        
        await inventory_balances.setLocation( data.location || null, {
            transaction,
        });
        
        await inventory_balances.setLot( data.lot || null, {
            transaction,
        });
        
        await inventory_balances.setOrganizations( data.organizations || 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_qty: item.on_hand_qty
            ||
            null
            ,
            
                allocated_qty: item.allocated_qty
            ||
            null
            ,
            
                available_qty: item.available_qty
            ||
            null
            ,
            
                uom: item.uom
            ||
            null
            ,
            
                as_of: item.as_of
            ||
            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 globalAccess = currentUser.app_role?.globalAccess;

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


        

        const updatePayload = {};
        
        if (data.on_hand_qty !== undefined) updatePayload.on_hand_qty = data.on_hand_qty;
        
        
        if (data.allocated_qty !== undefined) updatePayload.allocated_qty = data.allocated_qty;
        
        
        if (data.available_qty !== undefined) updatePayload.available_qty = data.available_qty;
        
        
        if (data.uom !== undefined) updatePayload.uom = data.uom;
        
        
        if (data.as_of !== undefined) updatePayload.as_of = data.as_of;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.material !== undefined) {
            await inventory_balances.setMaterial(
              
              data.material,
              
              { 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.organizations !== undefined) {
            await inventory_balances.setOrganizations(
              
              data.organizations,
              
              { 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.material = await inventory_balances.getMaterial({
            transaction
        });
        
        
        output.location = await inventory_balances.getLocation({
            transaction
        });
        
        
        output.lot = await inventory_balances.getLot({
            transaction
        });
        
        
        output.organizations = await inventory_balances.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.materials,
        as: 'material',
        
        where: filter.material ? {
          [Op.or]: [
            { id: { [Op.in]: filter.material.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.material.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.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.organizations,
        as: 'organizations',
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

            


      

      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'inventory_balances',
                        'uom',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

