export async function apiFetch(endpoint: string, options: RequestInit = {}) {
  const token = localStorage.getItem("access_token");

  const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}${endpoint}`, {
    ...options,
    credentials: "include", // Include cookies in requests
    headers: {
      ...(options.headers || {}),
      Authorization: token ? `Bearer ${token}` : "",
      "Content-Type": "application/json",
    },
  });

  if (res.status === 401) {
    // const refreshed = await tryRefreshToken(token);

    // if (refreshed) {
    //   const newToken = localStorage.getItem("access_token");

    //   const retryRes = await fetch(
    //     `${process.env.NEXT_PUBLIC_API_URL}${endpoint}`,
    //     {
    //       ...options,
    //       credentials: "include",
    //       headers: {
    //         ...(options.headers || {}),
    //         Authorization: newToken ? `Bearer ${newToken}` : "",
    //         "Content-Type": "application/json",
    //       },
    //     }
    //   );
    //   if (!retryRes.ok)
    //     throw new Error(`API Error ${retryRes.status}: ${retryRes.statusText}`);
    //   return retryRes.json();
    // } else {
    localStorage.clear();
    document.cookie = "role=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
    document.cookie =
      "refresh_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
    window.location.href = "/login";
    return;
    // }
  }

  if (!res.ok) throw new Error(`API Error ${res.status}: ${res.statusText}`);
  return res.json();
}

// async function tryRefreshToken(token: string | null): Promise<boolean> {
//   try {
//     const res = await fetch(
//       `${process.env.NEXT_PUBLIC_API_URL}/api/auth/refresh`,
//       {
//         method: "POST",
//         credentials: "include",
//         headers: {
//           Authorization: `Bearer ${token}`,
//           "Content-Type": "application/json",
//         },
//       }
//     );
//     console.log(res, "tryRefreshToken");

//     if (!res.ok) return false;

//     const data = await res.json();
//     console.log(data, "refresh data");
//     if (data.access_token) {
//       localStorage.setItem("access_token", data.access_token);
//       return true;
//     }

//     return false;
//   } catch {
//     return false;
//   }
// }
