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"); } // ✅ API Request Options const options: RequestInit = { method, headers: { Authorization: `Bearer ${authToken}`, "Content-Type": "application/json", }, credentials: "include", }; if (body) { options.body = JSON.stringify(body); } const API_URL = process.env.NEXT_PUBLIC_API_URL; if (!API_URL) throw new Error("NEXT_PUBLIC_API_URL is not set in environment variables"); const res = await fetchData(`${API_URL}${endpoint}`, 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 JSON response 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"); } };