const mongoose = require("mongoose");
const Order = mongoose.model("Orders");
const Customer = mongoose.model("Customer");
const User = mongoose.model("User") 
const BillHistory = mongoose.model("BillHistorys")
const Transaction = mongoose.model("Transaction")
const Adminuser = mongoose.model("Adminuser")
// const getGstData = require('../../apps/common/getGstData')
// const {messageBuilder} = require("../../apps/common/CommonFunctions")
// const Product = mongoose.model("Product");
const MarketplaceSubscribes = mongoose.model("MarketplaceSubscribes");
const Product = mongoose.model("Products");
// const PO = mongoose.model("PurchaseOrder");     
const CsvUpload = mongoose.model("CsvUpload");
const Orderprioritys = mongoose.model("Orderprioritys")
const Sfccategory = mongoose.model("Sfccategory")
const moment = require('moment-timezone');
const path = require('path');

const request = require('request-promise');
const csv = require('csvtojson');
const ObjectsToCsv = require('objects-to-csv');
const fs = require('fs');
const axios = require('axios');

const util = require('util');
const requestPromise = util.promisify(request);

let apikey = 'ac459774732706f8a0ff3cbf235af788';
let pass = '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';
let endpoint = 'products';
let store = 'de21cb-aa.myshopify.com';

let options1 = {
	'method' : 'POST',
	'url' : `https://${apikey}:${pass}@${store}/admin/api/2024-07/products.json`,
	'headers': {
		'Content-Type' : 'application/json'
	},
	body: JSON.stringify({
		// "product" : {
		// 	"title" : "Burton Custom Freestyle 151",
		// 	"body_html" : "<strong>Good snowboard!</strong>",
		// 	"vendor" : "Burton",
		// 	"product_type" : "Snowboard",
		// 	"category" : "New",
		// 	"variants": [
		// 		{
		// 		  "price": "100.00",
		// 		  "sku": "12345",
		// 		  "inventory_quantity": 5,
		// 		}
		// 	  ]
		// }
		"product": {
			"title": "Funny Glasses Straw Kids Party Favor DIY Crazy Drinking Straw Novelty - Clear",
			"body_html": "<p>\\r\\n\\t<strong>Description:</strong></p>\\r\\n<ul>\\r\\n\\t<li>\\r\\n\\t\\tA novelty gift for summer parties</li>\\r\\n\\t<li>\\r\\n\\t\\tGreat for children party bags and adult drinking games</li>\\r\\n\\t<li>\\r\\n\\t\\tFlexible straw is fixed on the glasses</li>\\r\\n\\t<li>\\r\\n\\t\\tPut on the glasses with the short end in your mouth and put the long end in your drink,then you can see the drink spiralling through the straw around your eyes</li>\\r\\n\\t<li>\\r\\n\\t\\tGlasses Size() :Approx.10.5x4.5cm/4.13x1.77inch</li>\\r\\n\\t<li>\\r\\n\\t\\tStraw Length:Approx.35cm /13.78inch,65cm/25.29inch</li>\\r\\n\\t<li>\\r\\n\\t\\tMaterial: Plastic</li>\\r\\n\\t<li>\\r\\n\\t\\tColor:Clear</li>\\r\\n</ul>\\r\\n<p>\\r\\n\\t<strong>Package Includes:</strong></p>\\r\\n<ul>\\r\\n\\t<li>\\r\\n\\t\\t1 Set of Glasses Straw</li>\\r\\n</ul>\\r\\n<p>\\r\\n\\t<span >Note: Please be reminded that due to lighting effects,monitor&#39;s brightness/contrast settings and <span>different batches</span> etc, the color  of the website&#39;s photo and the actual item could be slightly different.</span></p>\\r\\n",
			"vendor": "My Store",
			"product_type": "",
			"handle": "unique-handle-" + Date.now(),
			"variants": [
			  {
				"price": "1285.11",
				"sku": "78016113",
				"inventory_quantity": 23
			  }
			],
			"images": [
			  {
				"src": process.env.S3_BUCKET_FILE_URL+"/images/2024/6/cock-cotton-linen-throw-pillow-case-waist-cushion-cover-bed-sofa-decor/1719291926338xO8PSK.png"
			  }
			]
		  }
	})
};

exports.d2cProductCount = async (req,res) => {
	const resultCount = await Product.countDocuments({d2cStatus: 1}).exec();
    
	res.status(200).json({ message: resultCount })
}

exports.createProductCrone = async (req,res) => {

	// console.log(req.body.merchantId);

	// var merchantId = "666828c3f7fe9dcb4dc170fe";
	var merchantId = "66ea7696114d9d16b98c4b51";
	
	const userData = await User.find({_id: mongoose.Types.ObjectId(merchantId)}, {storeData:1});
	let storeDomain = '';
	let shopifyApiKey = '';
	let shopifySecretKey = '';

	if(userData.length>0){
		let storeData = userData[0].storeData;
		if(storeData.length>0){
			storeDomain = storeData[0].storeDomain;
			shopifyApiKey = storeData[0].shopifyApiKey;
			shopifySecretKey = storeData[0].shopifySecretKey;
		}else{
			res.status(500).send('Store data not found ');
		}
	}else{
		res.status(500).send('User not found ');
	}
	
	const productList = await Product.find({d2cStatus:0}).limit(500);
	// console.log(productList);
	// return false;

	const batchSize = 10;
	const promises = [];
	
	for (let i = 0; i < productList.length; i += batchSize) {
		const batch = productList.slice(i, i + batchSize);
		
		const promise = new Promise(async (resolve) => {

			// console.log(batch);
				
			try {

				const batchItemData = await Promise.all(batch.map(async (item) => {
					// console.log(item._id);

					// createProductShopify(item._id, storeDomain, shopifyApiKey, shopifySecretKey);

					let products = await Product.find({ "_id": mongoose.Types.ObjectId(item._id) });
					let tag1 = '';
					let tag2 = '';
					
					if (products.length > 0) {
						// Collect promises for each product creation
						const productCreationPromises = products.map(async item => {
						
							item.cat_id;
							
							const sfcCategoryList = await Sfccategory.find({cat_id: item.cat_id }, {str:1});
							if(sfcCategoryList.length>0){
								sfcCategoryList.forEach(catItem => {
									// console.log(catItem.str)
									var str = catItem.str.split(">");
									// console.log(catItem.str.split(">"))
									// console.log(str[0])
									// console.log(str.length)
									tag1 = str[0];

									if(str.length>1){
										tag2 = str[1];
									}
								})
							}

							// console.log(item.imgUrl)

							let mainImage = [];
							let productImage = item.imgUrl;
							if (productImage && productImage.length > 0) {
								productImage.forEach(function (pimage) {
									
									// console.log(pimage)
									
									// var imgData = { 'url': pimage.src, 'handle': handle };
									/*var imgData = { 'url': pimage.src };
									var imgpath = '';
									var varient_id = '';
									upload_image(imgData, function (result) {
										imgpath = result;
									});
									var imgres1 = { 'position': (parseInt(pimage.z_status) + 1), 'src': imgpath, 'varient_id': '' }
									mainImage.push(imgres1);*/

									var obj = {
										'src' : process.env.S3_BUCKET_FILE_URL  + "/" +  pimage.src
									}

									mainImage.push(obj);
								});
							}
							// console.log(mainImage);
							// return false;
							let options = {
								method: 'POST',
								url: `https://${shopifyApiKey}:${shopifySecretKey}@${storeDomain}/admin/api/2024-07/products.json`,
								headers: {
								'Content-Type': 'application/json'
								},
								body: JSON.stringify({
								product: {
									title: item.name,
									handle: item.name + Date.now(),
									body_html: item.description,
									vendor: "SFC",
									product_type: tag1,
									tags:[tag1, tag2],
									variants: [
									{
										price: item.sp,
										sku: item.code,
										inventory_quantity: item.quantity,
										quantity:1,
										inventory_management:'shopify'
									}
									],
									// images: [
									// {
									// 	src: process.env.S3_BUCKET_FILE_URL  + "/" +  item.imgUrl[0].src
									// }
									// ]
									images: mainImage
								}
								})
							};

							// console.log(options);

							// return false;

							// Return a promise for each request
							return requestPromise(options)
								.then(response => {
								const responseBody = JSON.parse(response.body);
								if (response.statusCode === 422) {
									throw new Error('Handle conflict error: ' + responseBody.errors.handle.join(', '));
								}
								if (response.statusCode >= 200 && response.statusCode < 300) {
									// console.log('productCategory1--'+item.category);

									// console.log('responseBody.product.id')
									// console.log(responseBody.product.id)
									// console.log(item._id)

									productStatusUpdate(item._id, responseBody.product.id);

									let category = item.category ? item.category : 'Other';
									let category_tag = tag1 ? tag1 : 'Other';

									// console.log(category_tag)

									let product_id = responseBody.product.id;
									collectionProductMapping(storeDomain, shopifyApiKey, shopifySecretKey, product_id, category_tag);

									return responseBody;
								}
								throw new Error(`Unexpected status code: ${response.statusCode}`);
								});

						});
						// await sleep(1000);
						
						return Promise.all(productCreationPromises);
					}

				}));

			} catch (error) {
				// console.error("Error processing item:", error);
				return null;
			}

		});
		promises.push(promise);
	}
}

// order create webhook routes
exports.createProduct = async (req,res) => {
    
	// console.log(req.body.merchantId);
	
	const userData = await User.find({_id: mongoose.Types.ObjectId(req.body.merchantId)}, {storeData:1});

	let storeDomain = '';
	let shopifyApiKey = '';
	let shopifySecretKey = '';

	if(userData.length>0){
		let storeData = userData[0].storeData;
		if(storeData.length>0){
			storeDomain = storeData[0].storeDomain;
			shopifyApiKey = storeData[0].shopifyApiKey;
			shopifySecretKey = storeData[0].shopifySecretKey;
		}else{
			res.status(500).send('Store data not found ');
		}
	}else{
		res.status(500).send('User not found ');
	}

	// return false;
	
	const ids = req.body.ids;

	let mIds = [...ids.map(x => mongoose.Types.ObjectId(x))];

	const subscribeProduct = await MarketplaceSubscribes.find({'pId': { $in: mIds }}, {sku:1});

	let productCategory = "";

	try {
		// Collect promises for finding products
		const productPromises = subscribeProduct.map(async (data) => {
		  let products = await Product.find({ code: data.sku });
		  let tag1 = '';
		  let tag2 = '';
		  
		  if (products.length > 0) {
			// Collect promises for each product creation
			const productCreationPromises = products.map(async item => {
			  
				item.cat_id;
				
				const sfcCategoryList = await Sfccategory.find({cat_id: item.cat_id }, {str:1});
				if(sfcCategoryList.length>0){
					sfcCategoryList.forEach(catItem => {
						// console.log(catItem.str)
						var str = catItem.str.split(">");
						// console.log(catItem.str.split(">"))
						// console.log(str[0])
						// console.log(str.length)
						tag1 = str[0];

						if(str.length>1){
							tag2 = str[1];
						}
					})
				}

				// console.log(sfcCategoryList)
				
				// return false;
				let options = {
				method: 'POST',
				url: `https://${shopifyApiKey}:${shopifySecretKey}@${storeDomain}/admin/api/2024-07/products.json`,
				headers: {
				  'Content-Type': 'application/json'
				},
				body: JSON.stringify({
				  product: {
					title: item.name,
					handle: item.name + Date.now(),
					body_html: item.description,
					vendor: "SFC",
					product_type: tag1,
					tags:[tag1, tag2],
					variants: [
					  {
						price: item.sp,
						sku: item.code,
						inventory_quantity: item.quantity,
						quantity:1,
						inventory_management:'shopify'
					  }
					],
					images: [
					  {
						src: process.env.S3_BUCKET_FILE_URL  + "/" +  item.imgUrl[0].src
					  }
					]
				  }
				})
			  };

			// productCategory = item.category;
			// console.log(item.category);
			
				//   console.log(process.env.S3_BUCKET_FILE_URL + "/" + item.imgUrl[0].src);
				//   return false;
				// Return a promise for each request
			  return requestPromise(options)
				.then(response => {
				  const responseBody = JSON.parse(response.body);
				  if (response.statusCode === 422) {
					throw new Error('Handle conflict error: ' + responseBody.errors.handle.join(', '));
				  }
				  if (response.statusCode >= 200 && response.statusCode < 300) {
					
					if(item.category!==''){
						// console.log('productCategory1');
						if(item.category!==''){
							
							let product_id = responseBody.product.id;
							collectionProductMapping(storeDomain, shopifyApiKey, shopifySecretKey, product_id, item.category);
						}else{
							let product_id = responseBody.product.id;
							collectionProductMapping(storeDomain, shopifyApiKey, shopifySecretKey, product_id, 'Other');
						}
					}else{
						let product_id = responseBody.product.id;
						collectionProductMapping(storeDomain, shopifyApiKey, shopifySecretKey, product_id, 'Other');
					}
					return responseBody;
				  }
				  throw new Error(`Unexpected status code: ${response.statusCode}`);
				});
			});
	
			return Promise.all(productCreationPromises);
		  }
		});

		const results = await Promise.all(productPromises);

		// console.log('productCategory');
		// console.log(productCategory);

		// return false;
		
		// Flatten results (if needed) and send a single response
		const flattenedResults = results.flat();
		
		res.status(200).send(flattenedResults);
	
	  } catch (error) {
		// console.error('Unexpected error:', error.message);
		if (!res.headersSent) {
		  res.status(500).send('An unexpected error occurred: ' + error.message);
		}
	  }
	
    
}

async function productStatusUpdate(productId, shopifyProductId){

	try{

		let updateObj = {
			d2cStatus: 1,
			shopifyProductId:shopifyProductId
		}

		// console.log(updateObj)
		
		await Product.updateOne({ "_id": mongoose.Types.ObjectId(productId) }, { $set: updateObj }, { upsert: false });

	}catch(err){

	}
}

async function createProductShopify(productId, storeDomain, shopifyApiKey, shopifySecretKey){
	const ids = productId;
	
	// let mIds = [...ids.map(x => mongoose.Types.ObjectId(x))];
	// console.log(mIds);
	// return false;
	// const subscribeProduct = await MarketplaceSubscribes.find({'pId': { $in: mIds }}, {sku:1});
	const subscribeProduct = await MarketplaceSubscribes.find({'pId': ids}, {sku:1});
	
	let productCategory = "";

	try {
		// Collect promises for finding products
		const productPromises = subscribeProduct.map(async (data) => {
		  let products = await Product.find({ code: data.sku });
		  let tag1 = '';
		  let tag2 = '';
		  
		  if (products.length > 0) {
			// Collect promises for each product creation
			const productCreationPromises = products.map(async item => {
			  
				item.cat_id;
				
				const sfcCategoryList = await Sfccategory.find({cat_id: item.cat_id }, {str:1});
				if(sfcCategoryList.length>0){
					sfcCategoryList.forEach(catItem => {
						// console.log(catItem.str)
						var str = catItem.str.split(">");
						// console.log(catItem.str.split(">"))
						// console.log(str[0])
						// console.log(str.length)
						tag1 = str[0];

						if(str.length>1){
							tag2 = str[1];
						}
					})
				}

				// console.log(sfcCategoryList)
				
				// return false;
				let options = {
				method: 'POST',
				url: `https://${shopifyApiKey}:${shopifySecretKey}@${storeDomain}/admin/api/2024-07/products.json`,
				headers: {
				  'Content-Type': 'application/json'
				},
				body: JSON.stringify({
				  product: {
					title: item.name,
					handle: item.name + Date.now(),
					body_html: item.description,
					vendor: "SFC",
					product_type: tag1,
					tags:[tag1, tag2],
					variants: [
					  {
						price: item.sp,
						sku: item.code,
						inventory_quantity: item.quantity,
						quantity:1,
						inventory_management:'shopify'
					  }
					],
					images: [
					  {
						src: process.env.S3_BUCKET_FILE_URL  + "/" +  item.imgUrl[0].src
					  }
					]
				  }
				})
			  };

			// productCategory = item.category;
			// console.log(item.category);
			
				//   console.log(process.env.S3_BUCKET_FILE_URL + "/" + item.imgUrl[0].src);
				//   return false;
				// Return a promise for each request
			  return requestPromise(options)
				.then(response => {
				  const responseBody = JSON.parse(response.body);
				  if (response.statusCode === 422) {
					throw new Error('Handle conflict error: ' + responseBody.errors.handle.join(', '));
				  }
				  if (response.statusCode >= 200 && response.statusCode < 300) {
					
					if(item.category!==''){
						// console.log('productCategory1--'+item.category);
						if(item.category!==''){
							
							let product_id = responseBody.product.id;
							collectionProductMapping(storeDomain, shopifyApiKey, shopifySecretKey, product_id, item.category);
						}else{
							let product_id = responseBody.product.id;
							collectionProductMapping(storeDomain, shopifyApiKey, shopifySecretKey, product_id, 'Other');
						}
					}else{
						let product_id = responseBody.product.id;
						collectionProductMapping(storeDomain, shopifyApiKey, shopifySecretKey, product_id, 'Other');
					}
					return responseBody;
				  }
				  throw new Error(`Unexpected status code: ${response.statusCode}`);
				});
			});
	
			return Promise.all(productCreationPromises);
		  }
		});

		const results = await Promise.all(productPromises);

		// console.log('productCategory');
		// console.log(productCategory);

		// return false;
		
		// Flatten results (if needed) and send a single response
		const flattenedResults = results.flat();
		
		res.status(200).send(flattenedResults);
	
	  } catch (error) {
		// console.error('Unexpected error:', error.message);
		if (!res.headersSent) {
		  res.status(500).send('An unexpected error occurred: ' + error.message);
		}
	  }
}

async function collectionProductMapping(storeDomain, shopifyApiKey, shopifySecretKey, productId, category){
	let collectionId = await get_collection_id(storeDomain, shopifyApiKey, shopifySecretKey , category);

	// console.log('collectionId');
	// console.log(collectionId);

	let collection_id = '';

	if(collectionId!=''){
		collection_id = collectionId;
	}else{
		let collectionId_other = await get_collection_id(storeDomain, shopifyApiKey, shopifySecretKey , 'Other');
		// console.log('collectionId_other--'+collectionId_other)
		collection_id = collectionId_other;
	}

	if(collection_id!==''){
		// console.log('collectionIdYes');
		try {
			const url = `https://${shopifyApiKey}:${shopifySecretKey}@${storeDomain}/admin/api/2024-07/collects.json`;
		
			const response = await axios.post(url, {
			  collect: {
				product_id: productId,
				collection_id: collection_id
			  }
			}, {
			  headers: {
				'Content-Type': 'application/json'
			  }
			});
		
			return response.data;
		  } catch (error) {
			if (error.response) {
			  // Response errors
			  const { status, data } = error.response;
			  if (status === 422) {
				// throw new Error('Handle conflict error: ' + data.errors.handle.join(', '));
			  } else {
				// throw new Error(`Unexpected status code: ${status}`);
			  }
			} else {
			  // Request errors
			  throw new Error(`Request failed: ${error.message}`);
			}
		  }
		
	}
}

async function get_collection_id(storeDomain, shopifyApiKey, shopifySecretKey, category) {
	try {
		const response = await axios.get(`https://${shopifyApiKey}:${shopifySecretKey}@${storeDomain}/admin/api/2024-07/custom_collections.json`, {
		headers: {
		  'Content-Type': 'application/json'
		}
		
	  });

	//   console.log('category--'+category);

	  /*response.data.custom_collections.forEach((item) => {
		// console.log(item.title+"==="+category)
		
		let title_result = item.title.toLowerCase();
		let category_result = category.toLowerCase();

		// console.log(typeof title_result)

		console.log(title_result+"==="+category_result)

		if(title_result.trim() === category_result.trim()){
			console.log('Yes')
			console.log(item.id)

			return item.id;
		}else{
			console.log('No');
			return false;
		}
	  })*/
	
	  // Find and return the collection ID
	  const collection = response.data.custom_collections.find(item => item.title.trim() === category.trim());
	//   console.log(collection)
	  if (collection) {
		return collection.id;
	  } else {
		return false;
	  }

	} catch (error) {
	//   console.error('Error fetching collections:', error.message);
	  return false;
	}
}

exports.updateProductPrice = async (req,res) => {
	
	const allProduct = await Product.find({d2cStatus: 1, priceUpdate:0}, {code:1, shopifyProductId:1, sp:1}).limit(500);
	// console.log(allProduct)
	try {
		// Collect promises for finding products
		
		if (allProduct.length > 0) {
			const productPromises = allProduct.map(async (data) => {
			
			
				// console.log(data.shopifyProductId)
				// console.log(data.sp)
				
				/*const productId = '8710663110869'; // Replace with the actual product ID
				const updateData = {
					// title: 'Updated Product Title',
					// body_html: 'Updated product description',
					// vendor: 'Updated Vendor',
					// product_type: 'Updated Product Type',
					// tags: ['Updated Tag1', 'Updated Tag2'],
					"variants": [
							{
								"price": "700.00",
								"sku": "54008952",
								// "inventory_quantity": 10,
							}
						]
				};
			
				updateProductData(productId, updateData)
					.then(updatedProduct => {
						// Handle successful update
						console.log('Updated product:', updatedProduct);
					})
					.catch(error => {
						// Handle error
						console.error('Failed to update product:', error);
					});*/
			

			});

			// const results = await Promise.all(productPromises);

			// const flattenedResults = results.flat();
			
			// res.status(200).send(flattenedResults);
		}

		
	
	  } catch (error) {
		// console.error('Unexpected error:', error.message);
		if (!res.headersSent) {
		  res.status(500).send('An unexpected error occurred: ' + error.message);
		}
	  }

	
	/************************ */
	
}

const updateProductData = async (productId, updateData) => {
    const options = {
        method: 'PUT',
        // url: `https://${shopifyApiKey}:${shopifySecretKey}@${storeDomain}/admin/api/2024-07/products/${productId}.json`,
        url: `https://6756a9b34f819addf3642900da703558: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@87f0cf-5f.myshopify.com/admin/api/2024-07/products/${productId}.json`,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            product: updateData
        })
    };

    try {
        const response = await requestPromise(options);
		// console.log(response)
        // const responseBody = JSON.parse(response);
        const responseBody = JSON.stringify(response);
        
        if (response.statusCode >= 200 && response.statusCode < 300) {
            // console.log('Product updated successfully:', responseBody);
            return responseBody;
        } else {
            throw new Error(`Unexpected status code: ${response.statusCode}`);
        }
    } catch (error) {
        // console.error('Error updating product:', error.message);
        throw error;
    }
};

/*exports.getCollections = async (req,res) => {
	try {
		const response = await axios.get(`https://19d2b20ffdd7801d5fb33bee29eed93a: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@56f777-74.myshopify.com/admin/api/2024-07/custom_collections.json`, {
		headers: {
		  'Content-Type': 'application/json'
		}
		
	  });
		
	//   console.log(response.data.custom_collections);
	  response.data.custom_collections.forEach((item) => {
		// console.log(item.title)
		// console.log(typeof item.title)
		if(item.title==='Toys & Hobbies'){
			console.log(item.id)

			return item.id;
		}else{
			return false;
		}
	  })
	  return false;
  
	  // Find and return the collection ID
	  const collection = response.data.custom_collections.find(item => item.title === category);
	  if (collection) {
		return collection.id;
	  } else {
		return false;
	  }
	} catch (error) {
	  console.error('Error fetching collections:', error.message);
	  return false;
	}
}*/
