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

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

        const inventory_movements = await db.inventory_movements.create(
            {
                id: data.id || undefined,
        
        movement_number: data.movement_number
        ||
        null
            ,
            
        movement_type: data.movement_type
        ||
        null
            ,
            
        movement_at: data.movement_at
        ||
        null
            ,
            
        quantity: data.quantity
        ||
        null
            ,
            
        reference: data.reference
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await inventory_movements.setItem( data.item || null, {
            transaction,
        });
        
        await inventory_movements.setUom( data.uom || null, {
            transaction,
        });
        
        await inventory_movements.setFrom_location( data.from_location || null, {
            transaction,
        });
        
        await inventory_movements.setTo_location( data.to_location || null, {
            transaction,
        });
        
        await inventory_movements.setLot( data.lot || null, {
            transaction,
        });
        
        await inventory_movements.setSerial( data.serial || null, {
            transaction,
        });
        
        await inventory_movements.setWork_order( data.work_order || null, {
            transaction,
        });
        
        await inventory_movements.setSupplier( data.supplier || null, {
            transaction,
        });
        
        await inventory_movements.setCustomer( data.customer || null, {
            transaction,
        });
        
        await inventory_movements.setReason_code( data.reason_code || null, {
            transaction,
        });
        
        await inventory_movements.setPerformed_by( data.performed_by || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.inventory_movements.getTableName(),
                belongsToColumn: 'documents',
                belongsToId: inventory_movements.id,
            },
            data.documents,
            options,
        );
        

        return inventory_movements;
    }
    

    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_movementsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                movement_number: item.movement_number
            ||
            null
            ,
            
                movement_type: item.movement_type
            ||
            null
            ,
            
                movement_at: item.movement_at
            ||
            null
            ,
            
                quantity: item.quantity
            ||
            null
            ,
            
                reference: item.reference
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < inventory_movements.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.inventory_movements.getTableName(),
                    belongsToColumn: 'documents',
                    belongsToId: inventory_movements[i].id,
                },
                data[i].documents,
                options,
            );
        }
        

        return inventory_movements;
    }

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

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


        

        const updatePayload = {};
        
        if (data.movement_number !== undefined) updatePayload.movement_number = data.movement_number;
        
        
        if (data.movement_type !== undefined) updatePayload.movement_type = data.movement_type;
        
        
        if (data.movement_at !== undefined) updatePayload.movement_at = data.movement_at;
        
        
        if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
        
        
        if (data.reference !== undefined) updatePayload.reference = data.reference;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.item !== undefined) {
            await inventory_movements.setItem(
              
              data.item,
              
              { transaction }
            );
        }
        
        if (data.uom !== undefined) {
            await inventory_movements.setUom(
              
              data.uom,
              
              { transaction }
            );
        }
        
        if (data.from_location !== undefined) {
            await inventory_movements.setFrom_location(
              
              data.from_location,
              
              { transaction }
            );
        }
        
        if (data.to_location !== undefined) {
            await inventory_movements.setTo_location(
              
              data.to_location,
              
              { transaction }
            );
        }
        
        if (data.lot !== undefined) {
            await inventory_movements.setLot(
              
              data.lot,
              
              { transaction }
            );
        }
        
        if (data.serial !== undefined) {
            await inventory_movements.setSerial(
              
              data.serial,
              
              { transaction }
            );
        }
        
        if (data.work_order !== undefined) {
            await inventory_movements.setWork_order(
              
              data.work_order,
              
              { transaction }
            );
        }
        
        if (data.supplier !== undefined) {
            await inventory_movements.setSupplier(
              
              data.supplier,
              
              { transaction }
            );
        }
        
        if (data.customer !== undefined) {
            await inventory_movements.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        
        if (data.reason_code !== undefined) {
            await inventory_movements.setReason_code(
              
              data.reason_code,
              
              { transaction }
            );
        }
        
        if (data.performed_by !== undefined) {
            await inventory_movements.setPerformed_by(
              
              data.performed_by,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.inventory_movements.getTableName(),
                belongsToColumn: 'documents',
                belongsToId: inventory_movements.id,
            },
            data.documents,
            options,
        );
        

        return inventory_movements;
    }

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

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

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


        return inventory_movements;
    }

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

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

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

        await inventory_movements.destroy({
            transaction
        });

        return inventory_movements;
    }

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

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

        if (!inventory_movements) {
            return inventory_movements;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.item = await inventory_movements.getItem({
            transaction
        });
        
        
        output.uom = await inventory_movements.getUom({
            transaction
        });
        
        
        output.from_location = await inventory_movements.getFrom_location({
            transaction
        });
        
        
        output.to_location = await inventory_movements.getTo_location({
            transaction
        });
        
        
        output.lot = await inventory_movements.getLot({
            transaction
        });
        
        
        output.serial = await inventory_movements.getSerial({
            transaction
        });
        
        
        output.work_order = await inventory_movements.getWork_order({
            transaction
        });
        
        
        output.supplier = await inventory_movements.getSupplier({
            transaction
        });
        
        
        output.customer = await inventory_movements.getCustomer({
            transaction
        });
        
        
        output.reason_code = await inventory_movements.getReason_code({
            transaction
        });
        
        
        output.performed_by = await inventory_movements.getPerformed_by({
            transaction
        });
        
        
        output.documents = await inventory_movements.getDocuments({
            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.uoms,
        as: 'uom',
        
        where: filter.uom ? {
          [Op.or]: [
            { id: { [Op.in]: filter.uom.split('|').map(term => Utils.uuid(term)) } },
            {
              uom_name: {
                [Op.or]: filter.uom.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)) } },
            {
              location_name: {
                [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)) } },
            {
              location_name: {
                [Op.or]: filter.to_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}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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

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



      {
        model: db.file,
        as: 'documents',
      },

    ];

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

            
            if (filter.movement_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inventory_movements',
                        'movement_number',
                        filter.movement_number,
                    ),
                };
            }
            
            if (filter.reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inventory_movements',
                        'reference',
                        filter.reference,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inventory_movements',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    movement_at: {
                    ...where.movement_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

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


      

      

      

      

      

      

      

      

      

      

      



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

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

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

    
};

