import { notFound } from 'next/navigation';

import { isSuperAdmin } from '@kit/admin';
import { getSupabaseServerClient } from '@kit/supabase/server-client';

import { isCompanyAdmin } from '../server/utils/is-company-admin';

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

/**
 * CompanyGuard is a server component wrapper that checks if the user is a company admin before rendering the component.
 * If the user is not a company admin, we redirect to a 404.
 * @param Component - The Page or Layout component to wrap
 */
export function CompanyGuard<Params extends object>(
  Component: LayoutOrPageComponent<Params>,
) {
  return async function AdminGuardServerComponentWrapper(params: Params) {
    //@ts-ignore
    const { account } = await params.params;
    const client = getSupabaseServerClient();
    const [isUserSuperAdmin, isUserCompanyAdmin] = await Promise.all([
      isSuperAdmin(client),
      isCompanyAdmin(client, account),
    ]);

    if (isUserSuperAdmin || isUserCompanyAdmin) {
      return <Component {...params} />;
    }
    // if the user is not a company admin, we redirect to a 404
    notFound();
  };
}
