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

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

        const inventory_batches = await db.inventory_batches.create(
            {
                id: data.id || undefined,
        
        batch_code: data.batch_code
        ||
        null
            ,
            
        manufactured_at: data.manufactured_at
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        quantity_on_hand: data.quantity_on_hand
        ||
        null
            ,
            
        unit_cost: data.unit_cost
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await inventory_batches.setProduct( data.product || null, {
            transaction,
        });
        
        await inventory_batches.setWarehouse( data.warehouse || null, {
            transaction,
        });
        
        await inventory_batches.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return inventory_batches;
    }
    

    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_batchesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                batch_code: item.batch_code
            ||
            null
            ,
            
                manufactured_at: item.manufactured_at
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                quantity_on_hand: item.quantity_on_hand
            ||
            null
            ,
            
                unit_cost: item.unit_cost
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return inventory_batches;
    }

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


        

        const updatePayload = {};
        
        if (data.batch_code !== undefined) updatePayload.batch_code = data.batch_code;
        
        
        if (data.manufactured_at !== undefined) updatePayload.manufactured_at = data.manufactured_at;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.quantity_on_hand !== undefined) updatePayload.quantity_on_hand = data.quantity_on_hand;
        
        
        if (data.unit_cost !== undefined) updatePayload.unit_cost = data.unit_cost;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.product !== undefined) {
            await inventory_batches.setProduct(
              
              data.product,
              
              { transaction }
            );
        }
        
        if (data.warehouse !== undefined) {
            await inventory_batches.setWarehouse(
              
              data.warehouse,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await inventory_batches.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return inventory_batches;
    }

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

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

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


        return inventory_batches;
    }

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

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

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

        await inventory_batches.destroy({
            transaction
        });

        return inventory_batches;
    }

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

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

        if (!inventory_batches) {
            return inventory_batches;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.inventory_transactions_batch = await inventory_batches.getInventory_transactions_batch({
            transaction
        });
        
        
        
        output.stock_adjustment_lines_batch = await inventory_batches.getStock_adjustment_lines_batch({
            transaction
        });
        
        
        
        output.transfer_lines_batch = await inventory_batches.getTransfer_lines_batch({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.sale_lines_batch = await inventory_batches.getSale_lines_batch({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.product = await inventory_batches.getProduct({
            transaction
        });
        
        
        output.warehouse = await inventory_batches.getWarehouse({
            transaction
        });
        
        
        output.organizations = await inventory_batches.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.products,
        as: 'product',
        
        where: filter.product ? {
          [Op.or]: [
            { id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
            {
              product_name: {
                [Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.warehouses,
        as: 'warehouse',
        
        where: filter.warehouse ? {
          [Op.or]: [
            { id: { [Op.in]: filter.warehouse.split('|').map(term => Utils.uuid(term)) } },
            {
              warehouse_name: {
                [Op.or]: filter.warehouse.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.batch_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inventory_batches',
                        'batch_code',
                        filter.batch_code,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            manufactured_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    expires_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

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

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

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

    
};

