const dbSAPPS = require("../../helpers/db");
require("dotenv").config();
const bcrypt = require("bcryptjs");
const axios = require("axios");
const { Op } = require("sequelize");
const { processPriceList } = require('./priceListProcessor'); // Sesuaikan path ke file processPriceList.js

module.exports = {
	getItemPriceList,
	getOptionItemPrices,
};

async function getItemPriceList(params) {
	try {
		// get
		const itemPrices = await axios.get(`${params.api_url}api/resource/Item%20Price`, {
			headers: {
				Authorization: `token ${params.api_key}:${params.api_secret}`,
				"Content-Type": "application/x-www-form-urlencoded, multipart/form-data",
				Accept: "application/json",
			},
			params: {
				fields: '["*"]',
				limit_start: "0",
				limit_page_length: "0",
				order_by: "item_code DESC",
				debug: "true",
			},
		});

		let processedData = [];
		processedData = processPriceList(itemPrices.data.data);

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

async function getOptionItemPrices(params) {
	try {
		// get
		const options = await axios.get(`${params.api_url}api/resource/Item%20Price`, {
			headers: {
				Authorization: `token ${params.api_key}:${params.api_secret}`,
				"Content-Type": "application/x-www-form-urlencoded, multipart/form-data",
				Accept: "application/json",
			},
			params: {
				fields: '["*"]',
				limit_start: "0",
				limit_page_length: "0",
				order_by: "modified DESC",
				debug: "true",
			},
		});

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