import https from "node:https";
import axios from "axios";
import { createLogger } from "../logger/logger.controller.js";
import { returnFunc } from "./returnHelper.utils.js";
import { tryCatch } from "./trycatch.utils.js";

type bodyData = any;

type Data = {
	endpoint: string;
	data?: bodyData[];
	method: "post" | "get" | "delete" | "patch";
};

// type ApiResponse<T = unknown> = {
// 	status: number;
// 	statusText: string;
// 	data: T;
// };

// create the test server stuff
const testServers = [
	{ token: "test1", port: 8940 },
	{ token: "test2", port: 8941 },
	{ token: "test3", port: 8942 },
];

const agent = new https.Agent({
	rejectUnauthorized: false,
});

export const prodEndpointCreation = async (endpoint: string) => {
	let url = "";
	//get the plant token
	const plantToken = process.env.PROD_PLANT_TOKEN ?? "test1";

	// check if we are a test server
	const testServer = testServers.some((server) => server.token === plantToken);

	// await db
	//     .select()
	//     .from(settings)
	//    .where(eq(settings.name, "dbServer"));

	if (testServer) {
		//filter out what testserver we are
		const test = testServers.filter((t) => t.token === plantToken);
		// "https://usmcd1vms036.alpla.net:8942/application/public/v1.0/DemandManagement/ORDERS"
		url = `https://${process.env.PROD_SERVER}.alpla.net:${test[0]?.port}/application${endpoint}`;
		return url;
	} else {
		url = `https://${plantToken}prod.alpla.net/application${endpoint}`;
		return url;
	}
};

/**
 *
 * @param data
 * @param timeoutDelay
 * @returns
 */
export const runProdApi = async (data: Data, name?: string) => {
	const log = createLogger({ module: "utils", subModule: "prodEndpoints" });
	const url = await prodEndpointCreation(data.endpoint);

	log.debug(
		{ stack: data },
		`Info passed over for ${name ? name : "Missing name"}`,
	);
	const { data: d, error } = await tryCatch(
		axios({
			method: data.method as string,
			url,
			data: data.data ? data.data[0] : undefined,
			headers: {
				"X-API-Key": process.env.TEC_API_KEY || "",
				"Content-Type": "application/json",
			},
			validateStatus: () => true,
			httpsAgent: agent,
		}),
	);

	switch (d?.status) {
		case 200:
			return returnFunc({
				success: true,
				level: "info",
				module: "utils",
				subModule: "prodEndpoint",
				message: "Data from prod endpoint",
				data: d.data,
				notify: false,
			});

		case 401:
			return returnFunc({
				success: false,
				level: "error",
				module: "utils",
				subModule: "prodEndpoint",
				message: "Error data from prod endpoint",
				data: d.data,
				notify: false,
			});
		case 400:
			return returnFunc({
				success: false,
				level: "error",
				module: "utils",
				subModule: "prodEndpoint",
				message: "Error data from prod endpoint",
				data: d.data,
				notify: false,
			});
		case 500:
			return returnFunc({
				success: false,
				level: "error",
				module: "utils",
				subModule: "prodEndpoint",
				message: "Error data from prod endpoint",
				data: d.data,
				notify: false,
			});
		default:
			returnFunc({
				success: false,
				level: "error",
				module: "utils",
				subModule: "prodEndpoint",
				message: "Unknown error encountered",
				data: d?.data as any,
				notify: false,
			});
	}

	if (error) {
		return returnFunc({
			success: true,
			level: "error",
			module: "utils",
			subModule: "prodEndpoint",
			message: "Failed to get data from the prod endpoint",
			data: error as any,
			notify: true,
		});
	}
};
