import { redirect } from "next/navigation";

import { getCurrentAuthContext } from "@/modules/core/server/auth";
import { listOperationalElders } from "@/modules/core/server/operations";
import { hasPermission } from "@/modules/core/server/permissions";
import { EldersClient } from "@/modules/elders/components/EldersClient";
import { listElderBedContextData } from "@/modules/operations/server/context";
import { getWorkspaceHref } from "@/modules/shared/lib/workspace-routing";

export default async function EldersPage(): Promise<React.ReactElement> {
  const context = await getCurrentAuthContext();
  if (!context) {
    redirect("/login");
  }

  if (!hasPermission(context.permissions, "elder:read")) {
    redirect(getWorkspaceHref(context.organization?.slug, "/dashboard"));
  }

  const organizationId = context.organization?.id;
  if (!organizationId) {
    redirect(getWorkspaceHref(context.organization?.slug, "/dashboard"));
  }

  const elders = await listOperationalElders(organizationId);
  const contextData = await listElderBedContextData({
    organizationId,
    permissions: context.permissions,
    elders,
    beds: [],
    admissions: [],
  });

  return <EldersClient elderContexts={contextData.elderContexts} initialElders={elders} permissions={context.permissions} />;
}
