//import path from "node:path";
//import { fileURLToPath } from "node:url";
import type { Express } from "express";

//const __filename = fileURLToPath(import.meta.url);
// const __dirname = path.dirname(__filename);

import os from "node:os";
import { apiReference } from "@scalar/express-api-reference";
// const port = 3000;
import type { OpenAPIV3_1 } from "openapi-types";
import { prodLoginSpec } from "../scaler/login.spec.js";
import { openDockApt } from "../scaler/opendockGetRelease.spec.js";
import { prodRestartSpec } from "../scaler/prodSqlRestart.spec.js";
import { prodStartSpec } from "../scaler/prodSqlStart.spec.js";
import { prodStopSpec } from "../scaler/prodSqlStop.spec.js";
import { prodRegisterSpec } from "../scaler/register.spec.js";
// all the specs
import { statusSpec } from "../scaler/stats.spec.js";
import { getAppVersion } from "../utils/version.utils.js";

export const openApiBase: OpenAPIV3_1.Document = {
	openapi: "3.1.0",
	info: {
		title: "LST API",
		version: (await getAppVersion()).version ?? "",
		description: "Label System Tracking API",
	},
	servers: [
		{
			// TODO: change this to the https:// if we are in production and port if not.
			url: `http://${os.hostname()}:3000${process.env.NODE_ENV?.trim() !== "production" ? "/lst" : "/"}`,
			description: "Development server",
		},
	],

	components: {
		securitySchemes: {
			bearerAuth: {
				type: "http",
				scheme: "bearer",
				bearerFormat: "JWT",
			},
			ApiKeyAuth: {
				type: "apiKey",
				description: "API key required for authentication",
				name: "api_key",
				in: "header",
			},
			basicAuth: {
				type: "http",
				scheme: "basic",
				description: "Basic authentication using username and password",
			},
			cookieAuth: {
				type: "apiKey",
				in: "cookie",
				name: "better-auth.session_token",
			},
		},
		// schemas: {
		// 	Error: {
		// 		type: "object",
		// 		properties: {
		// 			error: { type: "string" },
		// 			message: { type: "string" },
		// 		},
		// 	},
		// },.
	},
	// security: [
	// 	{
	// 		cookieAuth: [],
	// 		basicAuth: [],
	// 	},
	// ],
	tags: [
		{
			name: "Auth",
			description:
				"Authentication section where you get and create users and api keys",
		},
		{
			name: "System",
			description: "All system endpoints that will be available to run",
		},
		{
			name: "Utils",
			description: "All routes related to the utilities on the server",
		},
		{
			name: "Open Dock",
			description: "All routes related to the opendock on the server",
		},
		// { name: "TMS", description: "TMS integration" },
	],
	paths: {}, // Will be populated
};

export const setupApiDocsRoutes = (baseUrl: string, app: Express) => {
	// const mergedDatamart = {
	// 	"/api/datamart": {
	// 		...(cronerActiveJobs["/api/datamart"] ?? {}),
	// 		...(datamartAddSpec["/api/datamart"] ?? {}),
	// 		...(datamartUpdateSpec["/api/datamart"] ?? {}),
	// 	},
	// 	"/api/datamart/{name}": getDatamartSpec["/api/datamart/{name}"],
	// };

	// const mergeUtils = {
	// 	"/api/utils/croner": {
	// 		...(cronerActiveJobs["/api/utils/croner"] ?? {}),
	// 	},
	// 	"/api/utils/{name}": cronerActiveJobs["/api/utils/{name}"],
	// };

	const fullSpec = {
		...openApiBase,
		paths: {
			...statusSpec,
			...prodStartSpec,
			...prodStopSpec,
			...prodRestartSpec,
			...prodLoginSpec,
			...prodRegisterSpec,
			//...mergedDatamart,
			...openDockApt,

			// Add more specs here as you build features
		},
	};
	app.get(`${baseUrl}/api/docs.json`, (_, res) => {
		res.json(fullSpec);
	});

	app.use(
		`${baseUrl}/api/docs`,
		apiReference({
			url: `${baseUrl}/api/docs.json`,
			theme: "purple",

			darkMode: true,
			persistAuth: true,
			authentication: {
				securitySchemes: {
					httpBasic: {
						username: "username",
						password: "password",
					},
				},
			},
			defaultHttpClient: {
				targetKey: "node",
				clientKey: "axios",
			},

			documentDownloadType: "json",
			hideClientButton: true,
			hiddenClients: {
				// C
				c: ["libcurl"],
				// Clojure
				clojure: ["clj_http"],
				// C#
				// csharp: ["httpclient", "restsharp"],
				// Dart
				dart: ["http"],
				// F#
				fsharp: ["httpclient"],
				// Java
				java: ["asynchttp", "nethttp", "okhttp", "unirest"],
				// Objective-C
				objc: ["nsurlsession"],
				// OCaml
				ocaml: ["cohttp"],
				// PHP
				php: ["curl", "guzzle"],

				// R
				r: ["httr"],
				// Ruby
				ruby: ["native"],
				// Rust
				rust: ["reqwest"],
				// Swift
				swift: ["nsurlsession"],
			},
		}),
	);
};
