import { CustomerPageShell } from "@/app/customer/_components/customer-page-shell";
import { fetchAccessGroups, fetchAccessRouteCatalog } from "@/app/customer/_lib/admin/access-server-api";
import { loadAdminPageContext } from "@/app/customer/_lib/admin/load-admin-page-context";
import {
  canManageSection,
  pageKeysForSection,
} from "@/app/customer/_lib/admin/admin-section-permissions";

import { GroupsPageClient } from "./_components/groups-page-client";

type PageProps = {
  params: Promise<{ tenant: string }>;
};

export default async function CustomerAdminGroupsPage({ params }: Readonly<PageProps>) {
  const { tenant } = await params;
  const ctx = await loadAdminPageContext(tenant, {
    page: pageKeysForSection("groups"),
    label: "Groups",
  });
  if (ctx.denied) {
    return ctx.deniedView;
  }

  const [groupsResult, catalogResult] = await Promise.all([
    fetchAccessGroups(tenant),
    fetchAccessRouteCatalog(tenant),
  ]);

  return (
    <CustomerPageShell tutorialTarget="admin-roles">
      <GroupsPageClient
        tenant={tenant}
        initialGroups={groupsResult.items}
        appCatalog={catalogResult.apps}
        initialErrorMessage={groupsResult.errorMessage ?? catalogResult.errorMessage}
        canManageRoles={canManageSection("groups", ctx.capabilities)}
      />
    </CustomerPageShell>
  );
}
