import { fetchData } from '@/lib/data-service'; export const apiRequest = async (endpoint: string, method: string = "GET", body?: T | null) => { try { if (typeof document === "undefined") { throw new Error("API requests must be made from the client side."); } const authToken = document.cookie .split("; ") .find((row) => row.startsWith("Authorization=")) ?.split("=")[1]; if (!authToken){ document.location.href = "/login"; throw new Error("No authentication token found"); } const options: RequestInit = { method, headers: { Authorization: `Bearer ${authToken}`, "Content-Type": "application/json", }, credentials: "include", }; if (body) { options.body = JSON.stringify(body); } // Always use the Next.js API proxy to ensure all requests go through rewrites // Format the endpoint to ensure it has the /api prefix let url; if (endpoint.startsWith('/api/')) { url = endpoint; // Already has /api/ prefix } else { // Add /api prefix and ensure no duplicate slashes const cleanEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`; url = `/api${cleanEndpoint}`; } const res = await fetchData(url, options); if (!res) { const errorResponse = await res.json().catch(() => null); const errorMessage = errorResponse?.error || res.statusText || "Unknown error"; throw new Error(`Failed to ${method} ${endpoint}: ${errorMessage}`); } return res; } catch (error: unknown) { if (error instanceof Error) { console.error(`🚨 API Request Error: ${error.message}`); throw new Error(error.message); } console.error("❌ An unknown error occurred", error); throw new Error("An unknown error occurred"); } };