import { redirect } from "next/navigation";

import { getCurrentAuthContext } from "@/modules/core/server/auth";
import {
  listOperationalAdmissions,
  listOperationalBeds,
  listOperationalElders,
  listOperationalRooms,
} from "@/modules/core/server/operations";
import { hasPermission } from "@/modules/core/server/permissions";
import { BedsWorkspace } from "@/modules/facilities/components/BedsWorkspace";
import { listElderBedContextData } from "@/modules/operations/server/context";
import { getWorkspaceHref } from "@/modules/shared/lib/workspace-routing";

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

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

  const organizationId = context.organization?.id;
  const [rooms, beds, admissions, elders] = await Promise.all([
    listOperationalRooms(organizationId),
    listOperationalBeds(organizationId),
    listOperationalAdmissions(organizationId),
    listOperationalElders(organizationId),
  ]);
  const contextData = organizationId
    ? await listElderBedContextData({
        organizationId,
        permissions: context.permissions,
        elders,
        beds,
        admissions,
      })
    : { bedContexts: {}, elderContexts: {} };

  return (
    <BedsWorkspace
      bedContexts={contextData.bedContexts}
      initialAdmissions={admissions}
      initialBeds={beds}
      initialElders={elders}
      initialRooms={rooms}
      permissions={context.permissions}
    />
  );
}
