const express = require('express')
const mongoose = require('mongoose')
const router = express.Router()
const request = require('request-promise') 
const Supplier = require('../../models/User')
const SupplierCode = require('../../models/SupplierCode')
const AutoGeneratedSku = require('../../models/AutoGeneratedSku');
const updateProductsBarcode = async (products,productModel) =>{
	if(!products?.length){
		return 'No Product data';
	}
	return await Promise.allSettled(products.map(async (product)=>{
		let resData = {
			_id:product._id,
			message:"Done"
		}

		if(product.sid.toString() == "5ff1fb6cb5a4c4a27a0580dd"){
			resData.message = "Invalid Supplier Details - 5ff1fb6cb5a4c4a27a0580dd"
			return resData;
		}
	
		let productIds = product._id
	    let obj = {
	        barcode: 'blank'
	    } 
	    await productModel.updateOne({ "_id": productIds }, { $set: obj }, { upsert: false });
	    let supplierData = await SupplierCode.findOne({ "spId": product.sid } , {spCode : 1 , scCode : 1 , spId : 1})
		if(!supplierData){
			resData.message = "Invalid Supplier Details"
			return resData;
		}

		let supplierCode = supplierData.spCode;
		let supplierCountryCode = supplierData.scCode;
		let autoupBcArr = [];
		let autoGeneratedVal = await AutoGeneratedSku.count();
		autoGeneratedVal = autoGeneratedVal + 1;
		let upBc2 = autoGeneratedVal + 1000000;
		let upBcval = supplierCountryCode + "" + supplierCode + "" + upBc2
		let autoGenerated = new AutoGeneratedSku({
			'incNo': autoGeneratedVal
		})
		autoupBcArr.push(autoGenerated);

		let upBcs = product.varientArray.map((upBc) => {
			autoGeneratedVal = autoGeneratedVal + 1
			let upBc1 = autoGeneratedVal + 1000000;
			let finalBc = supplierCountryCode + "" + supplierCode + "" + upBc1
			let autoGenerated = new AutoGeneratedSku({
				'incNo': autoGeneratedVal
			})
			autoupBcArr.push(autoGenerated)
			upBc.barcode = finalBc
			return upBc
		})
		let barcodess = [];
		if(upBcs.length > 0){ 
			barcodess = upBcs.map((item) => { 
				return item.barcode
			});
		}else{  
			barcodess.push(upBcval ? upBcval : '')
		} 

		await AutoGeneratedSku.insertMany(autoupBcArr).then(() => {
			let updateVarObj = {
				barcode: upBcval,
				varientArray: upBcs, 
				vd: upBcs,
				barcodes :  barcodess
			}
			productModel.updateOne({ "_id": productIds }, { $set: updateVarObj }, { upsert: false }).exec().then(data => {
				
			});  
		});
		resData.barcodes = barcodess;

		return resData;
	}));
	
}

const updateBarcode = async (productModel) => {
	let sfcSupplierId = mongoose.Types.ObjectId('5ff1fb6cb5a4c4a27a0580dd');
    let products = await productModel.findOne({ barcode : '', "sid": {$ne: sfcSupplierId} });
	if(!products){
		return 'No Product data';
	}
	return await updateProductsBarcode([products],productModel);
}
 
module.exports = {updateBarcode,updateProductsBarcode}  