import { Suspense } from "react";
import { auth } from "@/auth";
import { HomePageClient } from "./home-page-client";

const SERVER_API_URL = process.env.SERVER_API_URL || "http://backend:8080";
const hasKeycloak = !!process.env.AUTH_KEYCLOAK_ISSUER;

interface Bookmark {
  id: number;
  title: string;
  url: string;
  description: string;
  icon: string;
  category: string;
}

async function fetchPublicBookmarks(): Promise<Bookmark[]> {
  try {
    const res = await fetch(`${SERVER_API_URL}/api/bookmarks/public`, {
      next: { revalidate: 0 },
    });
    if (!res.ok) return [];
    const data = await res.json();
    return data.bookmarks || [];
  } catch {
    return [];
  }
}

export default async function HomePage() {
  const session = await auth();
  const isAuthenticated = !!session?.user;
  const role = (session?.user as { role?: string } | undefined)?.role;
  const isAdmin = role === "admin";

  const bookmarks = await fetchPublicBookmarks();

  return (
    <Suspense>
      <HomePageClient
        isAuthenticated={isAuthenticated}
        isAdmin={isAdmin}
        hasKeycloak={hasKeycloak}
        bookmarks={bookmarks}
      />
    </Suspense>
  );
}
