
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_number: data.transaction_number
        ||
        null
            ,
            
        transaction_type: data.transaction_type
        ||
        null
            ,
            
        transaction_at: data.transaction_at
        ||
        null
            ,
            
        quantity: data.quantity
        ||
        null
            ,
            
        reference: data.reference
        ||
        null
            ,
            
        reason: data.reason
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await inventory_transactions.setMaterial( data.material || null, {
            transaction,
        });
        
        await inventory_transactions.setInventory_lot( data.inventory_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( data.performed_by || null, {
            transaction,
        });
        

        

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

        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_number: item.transaction_number
            ||
            null
            ,
            
                transaction_type: item.transaction_type
            ||
            null
            ,
            
                transaction_at: item.transaction_at
            ||
            null
            ,
            
                quantity: item.quantity
            ||
            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
        
        for (let i = 0; i < inventory_transactions.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.inventory_transactions.getTableName(),
                    belongsToColumn: 'attachments',
                    belongsToId: inventory_transactions[i].id,
                },
                data[i].attachments,
                options,
            );
        }
        

        return inventory_transactions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.transaction_number !== undefined) updatePayload.transaction_number = data.transaction_number;
        
        
        if (data.transaction_type !== undefined) updatePayload.transaction_type = data.transaction_type;
        
        
        if (data.transaction_at !== undefined) updatePayload.transaction_at = data.transaction_at;
        
        
        if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
        
        
        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.material !== undefined) {
            await inventory_transactions.setMaterial(
              
              data.material,
              
              { transaction }
            );
        }
        
        if (data.inventory_lot !== undefined) {
            await inventory_transactions.setInventory_lot(
              
              data.inventory_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 !== undefined) {
            await inventory_transactions.setPerformed_by(
              
              data.performed_by,
              
              { transaction }
            );
        }
        

        
        

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

        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.material = await inventory_transactions.getMaterial({
            transaction
        });
        
        
        output.inventory_lot = await inventory_transactions.getInventory_lot({
            transaction
        });
        
        
        output.from_location = await inventory_transactions.getFrom_location({
            transaction
        });
        
        
        output.to_location = await inventory_transactions.getTo_location({
            transaction
        });
        
        
        output.performed_by = await inventory_transactions.getPerformed_by({
            transaction
        });
        
        
        output.attachments = await inventory_transactions.getAttachments({
            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.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.inventory_lots,
        as: 'inventory_lot',
        
        where: filter.inventory_lot ? {
          [Op.or]: [
            { id: { [Op.in]: filter.inventory_lot.split('|').map(term => Utils.uuid(term)) } },
            {
              lot_number: {
                [Op.or]: filter.inventory_lot.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.storage_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.storage_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',
        
        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: 'attachments',
      },

    ];

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

            
            if (filter.transaction_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inventory_transactions',
                        'transaction_number',
                        filter.transaction_number,
                    ),
                };
            }
            
            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.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.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.transaction_type) {
                where = {
                    ...where,
                transaction_type: filter.transaction_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_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, ) {
        let where = {};
        
        

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

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

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

    
};

