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

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

        const inventory_lots = await db.inventory_lots.create(
            {
                id: data.id || undefined,
        
        lot_number: data.lot_number
        ||
        null
            ,
            
        supplier_lot_number: data.supplier_lot_number
        ||
        null
            ,
            
        received_at: data.received_at
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        quality_status: data.quality_status
        ||
        null
            ,
            
        on_hand_qty: data.on_hand_qty
        ||
        null
            ,
            
        allocated_qty: data.allocated_qty
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await inventory_lots.setItem( data.item || null, {
            transaction,
        });
        
        await inventory_lots.setWarehouse( data.warehouse || null, {
            transaction,
        });
        
        await inventory_lots.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return inventory_lots;
    }
    

    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_lotsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                lot_number: item.lot_number
            ||
            null
            ,
            
                supplier_lot_number: item.supplier_lot_number
            ||
            null
            ,
            
                received_at: item.received_at
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                quality_status: item.quality_status
            ||
            null
            ,
            
                on_hand_qty: item.on_hand_qty
            ||
            null
            ,
            
                allocated_qty: item.allocated_qty
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return inventory_lots;
    }

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


        

        const updatePayload = {};
        
        if (data.lot_number !== undefined) updatePayload.lot_number = data.lot_number;
        
        
        if (data.supplier_lot_number !== undefined) updatePayload.supplier_lot_number = data.supplier_lot_number;
        
        
        if (data.received_at !== undefined) updatePayload.received_at = data.received_at;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.quality_status !== undefined) updatePayload.quality_status = data.quality_status;
        
        
        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;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.item !== undefined) {
            await inventory_lots.setItem(
              
              data.item,
              
              { transaction }
            );
        }
        
        if (data.warehouse !== undefined) {
            await inventory_lots.setWarehouse(
              
              data.warehouse,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await inventory_lots.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return inventory_lots;
    }

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

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

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


        return inventory_lots;
    }

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

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

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

        await inventory_lots.destroy({
            transaction
        });

        return inventory_lots;
    }

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

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

        if (!inventory_lots) {
            return inventory_lots;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.inventory_transactions_lot = await inventory_lots.getInventory_transactions_lot({
            transaction
        });
        
        
        
        
        output.material_allocations_lot = await inventory_lots.getMaterial_allocations_lot({
            transaction
        });
        
        
        output.quality_inspections_lot = await inventory_lots.getQuality_inspections_lot({
            transaction
        });
        
        
        output.nonconformances_lot = await inventory_lots.getNonconformances_lot({
            transaction
        });
        
        
        
        
        
        output.item = await inventory_lots.getItem({
            transaction
        });
        
        
        output.warehouse = await inventory_lots.getWarehouse({
            transaction
        });
        
        
        output.certificates = await inventory_lots.getCertificates({
            transaction
        });
        
        
        output.organizations = await inventory_lots.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.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.warehouses,
        as: 'warehouse',
        
        where: filter.warehouse ? {
          [Op.or]: [
            { id: { [Op.in]: filter.warehouse.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.warehouse.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.organizations,
        as: 'organizations',
        
      },



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

    ];

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

            
            if (filter.lot_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inventory_lots',
                        'lot_number',
                        filter.lot_number,
                    ),
                };
            }
            
            if (filter.supplier_lot_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inventory_lots',
                        'supplier_lot_number',
                        filter.supplier_lot_number,
                    ),
                };
            }
            

            
            

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

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

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

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


      

      

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

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

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

    
};

