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

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

        const inventory_transactions = await db.inventory_transactions.create(
            {
                id: data.id || undefined,
        
        transaction_type: data.transaction_type
        ||
        null
            ,
            
        quantity: data.quantity
        ||
        null
            ,
            
        uom: data.uom
        ||
        null
            ,
            
        transaction_at: data.transaction_at
        ||
        null
            ,
            
        reference: data.reference
        ||
        null
            ,
            
        reason: data.reason
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await inventory_transactions.setPlant( data.plant || null, {
            transaction,
        });
        
        await inventory_transactions.setItem( data.item || null, {
            transaction,
        });
        
        await inventory_transactions.setLot( data.lot || null, {
            transaction,
        });
        
        await inventory_transactions.setFrom_location( data.from_location || null, {
            transaction,
        });
        
        await inventory_transactions.setTo_location( data.to_location || null, {
            transaction,
        });
        
        await inventory_transactions.setPerformed_by_user( data.performed_by_user || null, {
            transaction,
        });
        
        await inventory_transactions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return inventory_transactions;
    }
    

    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_transactionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                transaction_type: item.transaction_type
            ||
            null
            ,
            
                quantity: item.quantity
            ||
            null
            ,
            
                uom: item.uom
            ||
            null
            ,
            
                transaction_at: item.transaction_at
            ||
            null
            ,
            
                reference: item.reference
            ||
            null
            ,
            
                reason: item.reason
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return inventory_transactions;
    }

    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_transactions = await db.inventory_transactions.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.transaction_type !== undefined) updatePayload.transaction_type = data.transaction_type;
        
        
        if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
        
        
        if (data.uom !== undefined) updatePayload.uom = data.uom;
        
        
        if (data.transaction_at !== undefined) updatePayload.transaction_at = data.transaction_at;
        
        
        if (data.reference !== undefined) updatePayload.reference = data.reference;
        
        
        if (data.reason !== undefined) updatePayload.reason = data.reason;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.plant !== undefined) {
            await inventory_transactions.setPlant(
              
              data.plant,
              
              { transaction }
            );
        }
        
        if (data.item !== undefined) {
            await inventory_transactions.setItem(
              
              data.item,
              
              { transaction }
            );
        }
        
        if (data.lot !== undefined) {
            await inventory_transactions.setLot(
              
              data.lot,
              
              { transaction }
            );
        }
        
        if (data.from_location !== undefined) {
            await inventory_transactions.setFrom_location(
              
              data.from_location,
              
              { transaction }
            );
        }
        
        if (data.to_location !== undefined) {
            await inventory_transactions.setTo_location(
              
              data.to_location,
              
              { transaction }
            );
        }
        
        if (data.performed_by_user !== undefined) {
            await inventory_transactions.setPerformed_by_user(
              
              data.performed_by_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await inventory_transactions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return inventory_transactions;
    }

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

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

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


        return inventory_transactions;
    }

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

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

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

        await inventory_transactions.destroy({
            transaction
        });

        return inventory_transactions;
    }

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

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

        if (!inventory_transactions) {
            return inventory_transactions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.plant = await inventory_transactions.getPlant({
            transaction
        });
        
        
        output.item = await inventory_transactions.getItem({
            transaction
        });
        
        
        output.lot = await inventory_transactions.getLot({
            transaction
        });
        
        
        output.from_location = await inventory_transactions.getFrom_location({
            transaction
        });
        
        
        output.to_location = await inventory_transactions.getTo_location({
            transaction
        });
        
        
        output.performed_by_user = await inventory_transactions.getPerformed_by_user({
            transaction
        });
        
        
        output.organizations = await inventory_transactions.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.plants,
        as: 'plant',
        
        where: filter.plant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.plant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.plant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        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.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.locations,
        as: 'from_location',
        
        where: filter.from_location ? {
          [Op.or]: [
            { id: { [Op.in]: filter.from_location.split('|').map(term => Utils.uuid(term)) } },
            {
              code: {
                [Op.or]: filter.from_location.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.users,
        as: 'performed_by_user',
        
        where: filter.performed_by_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.performed_by_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.performed_by_user.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_transactions',
                        'uom',
                        filter.uom,
                    ),
                };
            }
            
            if (filter.reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inventory_transactions',
                        'reference',
                        filter.reference,
                    ),
                };
            }
            
            if (filter.reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inventory_transactions',
                        'reason',
                        filter.reason,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      

      

      

      

      

      

      
      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_transactions.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_transactions',
                        'reference',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

