require("dotenv").config();
const dbSAPPS = require("../helpers/db");
const bcrypt = require("bcryptjs");
const axios = require("axios");
const { Op } = require("sequelize");

module.exports = {
	reportERPNextStockBalance,
};

function currencyFormat(num) {
	return 'Rp. ' + num.toFixed(0).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}

async function reportERPNextStockBalance(params) {
	try {
		const stockBalances = await axios.get(
			`${params.api_url}api/method/custom_app.stock_balance`,
			{
				headers: {
					Authorization: `token ${params.api_key}:${params.api_secret}`,
					"Content-Type":
						"application/x-www-form-urlencoded, multipart/form-data",
					Accept: "application/json",
				},
				params: {
					item_code: params.item_code || "",
					company: params.company || "",
					warehouse: params.warehouse || "",
					from_date: params.from_date || "",
					to_date: params.to_date || "",
				},
			}
		);

		const result = stockBalances.data.stock_data.reduce((acc, item) => {
			item.batch_details.forEach((batch) => {
				acc.push({
					item_code: item.item_code,
					item_name: item.item_name,
					sku_code: item.sku_code,
					alternative_sku_code: item.alternative_sku_code,
					nomor_izin_edar: item.nomor_izin_edar,
					item_group: item.item_group,
					stock_uom: item.stock_uom,
					custom_supplier: item.custom_supplier,
					warehouse: item.warehouse,
					warehouse_name: item.warehouse_name,
					company: item.company,
					opening_qty: batch.opening_qty,
					in_qty: batch.in_qty,
					out_qty: batch.out_qty,
					balance_qty: batch.balance_qty,
					ending_qty: batch.ending_qty,
					batch_no: batch.batch_no,
					expiry_date: batch.expiry_date,
					manufacturing_date: batch.manufacturing_date,
					days_in_stock: batch.days_in_stock,
					ageing: batch.ageing,
					price_list_rate: item.price_list_rate ? currencyFormat(item.price_list_rate) : 0,
				});
			});

			if (item.serial_details.length > 0) {
				item.serial_details.forEach((serial) => {
					acc.push({
						item_code: item.item_code,
						item_name: item.item_name,
						sku_code: item.sku_code,
						alternative_sku_code: item.alternative_sku_code,
						nomor_izin_edar: item.nomor_izin_edar,
						item_group: item.item_group,
						stock_uom: item.stock_uom,
						custom_supplier: item.custom_supplier,
						warehouse: item.warehouse,
						warehouse_name: item.warehouse_name,
						company: item.company,
						opening_qty: 0,
						in_qty: 0,
						out_qty: 0,
						balance_qty: 1,
						ending_qty: 1,
						serial_no: serial.serial_no,
						expiry_date: serial.expiry_date,
						manufacturing_date: serial.manufacturing_date,
						days_in_stock: serial.days_in_stock,
						ageing: serial.ageing,
						price_list_rate: item.price_list_rate ? currencyFormat(item.price_list_rate) : 0,
					});
				});
			}

			return acc;
		}, []);

		return {
			stockBalances: result || [],
			success: true,
			message: "Loaded successfully!",
		};
	} catch (error) {
		const errorMessage = error?.message || "Failed to load, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}
