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

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";

  const baseUrl = getBaseUrl();

  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();
  // 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={users} />
    </div>
  );
}
