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

module.exports = {
	getBudgetList,
	getOptionBudgets,
	getBudgetAccount,
};

async function getBudgetList(params) {
	try {
		// get
		const budgets = await axios.get(`${params.api_url}api/resource/Budget`, {
			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",
				filters: '[["docstatus","=",1]]',
			},
		});

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

async function getOptionBudgets(params) {
	try {
		// get
		const options = await axios.get(`${params.api_url}api/resource/Budget`, {
			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",
				filters: '[["docstatus","=",1]]',
			},
		});

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

async function getBudgetAccount(params) {
	try {
		// get
		const budgets = await axios.get(`${params.api_url}api/method/custom_app.get_budget_account`, {
			headers: {
				Authorization: `token ${params.api_key}:${params.api_secret}`,
				"Content-Type": "application/x-www-form-urlencoded, multipart/form-data",
				Accept: "application/json",
			},
			params: {
				name: params.name,
			},
		});

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