/**
 * This will fire the endpoints
 * we only need the endpoint url grabbed from swagger
 * and the data to be passed over
 */

import axios, { type Method } from "axios";
import { eq } from "drizzle-orm";
import https from "https";
import { db } from "../db/db.js";
import { settings } from "../db/schema/settings.js";
import { createLogger } from "../logger/logger.js";
import { tryCatch } from "./tryCatch.js";

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

export const prodEndpoint = async <T>(
	method: Method,
	endpoint: string,
	data?: T,
) => {
	const log = createLogger({ module: "pkg", subModule: "prodEndpoints" });
	// example url "https://usmcd1vms036.alpla.net:8942/application/public/v1.0/DemandManagement/ORDERS"
	let url = "";

	// as a reminder when we look for specific like below it will come over as an array this is due to more than one item could be found
	const plantToken = await db
		.select()
		.from(settings)
		.where(eq(settings.name, "plantToken"));

	const testServer = testServers.some(
		(server) => server.token === plantToken[0]?.value,
	);
	const server = 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[0].value);
		url = `https://${server[0]?.value}.alpla.net:${test[0]?.port}/application${endpoint}`;
	} else {
		url = `https://${plantToken[0]?.value}prod.alpla.net/application${endpoint}`;
	}

	// create the axio instance
	const axiosInstance = axios.create({
		httpsAgent: new https.Agent({ rejectUnauthorized: false }),
		withCredentials: true,
		headers: {
			"X-API-Key": process.env.TEC_API_KEY || "",
			"Content-Type": "application/json",
		},
	});

	const { data: api, error: apiError } = (await tryCatch(
		axiosInstance({
			method,
			url: url,
			...(data && { data }),
		}),
	)) as any;

	if (apiError) {
		log.error(
			{ error: apiError?.response?.data },
			"There was an error running the endpoint",
		);
		return {
			success: false,
			message: "There was an error processing the endpoint",
			data: apiError.response.data,
		};
	}

	if (api) {
		return {
			success: true,
			message: "Prod endpoint processed",
			data: api.data,
		};
	}
};
