// ajaxInterceptor.ts
export interface AjaxEventDetail {
	url?: string;
	response: string;
	status: number;
}

export function setupAjaxInterceptor(onComplete: (detail: AjaxEventDetail) => void): void {
	const originalOpen = XMLHttpRequest.prototype.open;
	const originalSend = XMLHttpRequest.prototype.send;

	interface PatchedXMLHttpRequest extends XMLHttpRequest {
		_url?: string;
	}

	// Override the `open` method to capture the request URL
	XMLHttpRequest.prototype.open = function (
		this: PatchedXMLHttpRequest,
		method: string,
		url: string,
		...rest: any[]
	) {
		this._url = url; // Save the URL for reference
		return originalOpen.apply(this, [method, url, ...rest] as any);
	};

	// Override the `send` method to listen for request completion
	XMLHttpRequest.prototype.send = function (this: PatchedXMLHttpRequest, ...args: any[]) {
		const onLoad = () => {
			const detail: AjaxEventDetail = {
				url: this._url,
				response: this.responseText,
				status: this.status,
			};

			// Call the provided callback with the AJAX details
			onComplete(detail);
		};
		this.addEventListener("load", onLoad);
		return originalSend.apply(this, args as any);
	};
}

// import { setupAjaxInterceptor, AjaxEventDetail } from "./ajaxInterceptor";

// Define your callback function to handle AJAX completions
// function handleAjaxComplete(detail: AjaxEventDetail) {
// 	console.log("AJAX Complete:", detail);
// Perform any global logging, analytics, or additional logic here
// }

// Set up the AJAX interceptor
// setupAjaxInterceptor(handleAjaxComplete);
