import { LabSshAuthorizationApproveForm } from "@/components/pages/lab-ssh-auth/approve-form";
import { getSshAuth } from "@/lib/api/labs";
import { cachedGetMe } from "@/lib/api/server-labs";
import { isServerError } from "@/lib/errors";
import { notFound, redirect } from "next/navigation";

export default async function LabSshAuthorizationPage({
  searchParams,
}: {
  searchParams?: Promise<{ id?: string | string[] | undefined }>;
}) {
  const id = (await searchParams)?.["id"];

  if (typeof id !== "string") {
    notFound();
  }

  const me = await cachedGetMe();

  if (!me) {
    redirect(
      `/login?redirect_uri=${encodeURIComponent("/lab-ssh/authorization?id=" + id)}`
    );
  }

  try {
    await getSshAuth(id);
    return <LabSshAuthorizationApproveForm id={id} />;
  } catch (e) {
    if (isServerError(e, [401, 403, 404])) {
      notFound();
    }
    return Promise.reject(e);
  }
}
