import { notFound } from 'next/navigation';

import { isDoctor } from '@kit/doctor/lib/server/utils/is-doctor';
import { getSupabaseServerClient } from '@kit/supabase/server-client';

type LayoutOrPageComponent<Params> = React.ComponentType<Params>;

/**
 * DoctorGuard is a server component wrapper that checks if the user is a doctor before rendering the component.
 * If the user is not a doctor, we redirect to a 404.
 * @param Component - The Page or Layout component to wrap
 */
export function DoctorGuard<Params extends object>(
  Component: LayoutOrPageComponent<Params>,
) {
  return async function DoctorGuardServerComponentWrapper(params: Params) {
    const client = getSupabaseServerClient();
    const isUserDoctor = await isDoctor(client);

    // if the user is not a super-admin, we redirect to a 404
    if (!isUserDoctor) {
      notFound();
    }

    return <Component {...params} />;
  };
}
