import Users from "@/app/features/Pages/Admin/Users/users";
import { cookies } from "next/headers";

export default async function BackOfficeUsersPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  // Await searchParams and extract pagination
  const params = await searchParams;
  const limit = params.limit || "10";
  const page = params.page || "1";

  // Build absolute URL for server-side fetch
  // In server components, fetch requires absolute URLs
  const port = process.env.PORT || "3000";
  const baseUrl =
    process.env.NEXT_PUBLIC_BASE_URL ||
    (process.env.VERCEL_URL
      ? `https://${process.env.VERCEL_URL}`
      : `http://localhost:${port}`);

  const url = new URL(`${baseUrl}/api/dashboard/admin/users`);
  url.searchParams.set("limit", typeof limit === "string" ? limit : limit[0]);
  url.searchParams.set("page", typeof page === "string" ? page : page[0]);

  // Forward cookies for auth when calling the internal API route
  const cookieStore = await cookies();
  const cookieHeader = cookieStore
    .getAll()
    .map((c: { name: string; value: string }) => `${c.name}=${c.value}`)
    .join("; ");

  const res = await fetch(url.toString(), {
    headers: {
      Cookie: cookieHeader,
    },
    cache: "no-store",
  });

  if (!res.ok) {
    console.error("Failed to fetch users:", res.status, res.statusText);
    return (
      <div>
        <Users users={[]} />
      </div>
    );
  }

  const data = await res.json();
  console.log("[DEBUG] - DATA", data);
  // Handle different response structures: could be array directly, or wrapped in data/users property
  // const users = Array.isArray(data) ? data : data.users || data.data || [];

  return (
    <div>
      <Users users={data?.users} />
    </div>
  );
}
