
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_on: data.received_on
        ||
        null
            ,
            
        manufactured_on: data.manufactured_on
        ||
        null
            ,
            
        expires_on: data.expires_on
        ||
        null
            ,
            
        lot_status: data.lot_status
        ||
        null
            ,
            
        certificate_number: data.certificate_number
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await inventory_lots.setMaterial( data.material || null, {
            transaction,
        });
        
        await inventory_lots.setSupplier( data.supplier || 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_on: item.received_on
            ||
            null
            ,
            
                manufactured_on: item.manufactured_on
            ||
            null
            ,
            
                expires_on: item.expires_on
            ||
            null
            ,
            
                lot_status: item.lot_status
            ||
            null
            ,
            
                certificate_number: item.certificate_number
            ||
            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_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 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_on !== undefined) updatePayload.received_on = data.received_on;
        
        
        if (data.manufactured_on !== undefined) updatePayload.manufactured_on = data.manufactured_on;
        
        
        if (data.expires_on !== undefined) updatePayload.expires_on = data.expires_on;
        
        
        if (data.lot_status !== undefined) updatePayload.lot_status = data.lot_status;
        
        
        if (data.certificate_number !== undefined) updatePayload.certificate_number = data.certificate_number;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.material !== undefined) {
            await inventory_lots.setMaterial(
              
              data.material,
              
              { transaction }
            );
        }
        
        if (data.supplier !== undefined) {
            await inventory_lots.setSupplier(
              
              data.supplier,
              
              { 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_balances_inventory_lot = await inventory_lots.getInventory_balances_inventory_lot({
            transaction
        });
        
        
        output.inventory_transactions_inventory_lot = await inventory_lots.getInventory_transactions_inventory_lot({
            transaction
        });
        
        
        
        
        
        
        
        
        output.production_material_issues_inventory_lot = await inventory_lots.getProduction_material_issues_inventory_lot({
            transaction
        });
        
        
        
        output.qa_inspections_inventory_lot = await inventory_lots.getQa_inspections_inventory_lot({
            transaction
        });
        
        
        
        
        
        output.nonconformances_inventory_lot = await inventory_lots.getNonconformances_inventory_lot({
            transaction
        });
        
        
        
        
        
        output.material = await inventory_lots.getMaterial({
            transaction
        });
        
        
        output.supplier = await inventory_lots.getSupplier({
            transaction
        });
        
        
        output.certificates = await inventory_lots.getCertificates({
            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.suppliers,
        as: 'supplier',
        
        where: filter.supplier ? {
          [Op.or]: [
            { id: { [Op.in]: filter.supplier.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.supplier.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



      {
        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.certificate_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inventory_lots',
                        'certificate_number',
                        filter.certificate_number,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inventory_lots',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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


      

      



            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_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, ) {
        let where = {};
        
        

        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,
        }));
    }

    
};

