// Boots the self-hosted Swagger UI (the app's CSP forbids inline scripts and CDNs).
// "Try it out" calls run same-origin, so the browser session cookie authenticates them;
// write endpoints additionally need the x-csrf-token header, which is injected below.
/* global SwaggerUIBundle */
const csrf = () =>
	document.cookie
		.split("; ")
		.find((v) => v.startsWith("rp_csrf="))
		?.split("=")[1] || "";

window.addEventListener("DOMContentLoaded", () => {
	SwaggerUIBundle({
		url: "/api/openapi.json",
		dom_id: "#swagger-ui",
		docExpansion: "none",
		defaultModelsExpandDepth: -1,
		requestInterceptor: (request) => {
			if (!/^(GET|HEAD)$/i.test(request.method) && !request.headers.Authorization)
				request.headers["x-csrf-token"] = csrf();
			return request;
		},
	});
});
