import { redirect } from "next/navigation";

import { KnowledgeManagementClient } from "@/modules/ai/components/KnowledgeManagementClient";
import { listKnowledgeEntries } from "@/modules/ai/server/knowledge";
import { getCurrentAuthContext } from "@/modules/core/server/auth";
import { hasPermission } from "@/modules/core/server/permissions";
import { getWorkspaceHref } from "@/modules/shared/lib/workspace-routing";

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

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

  const entries = await listKnowledgeEntries(context);
  return <KnowledgeManagementClient initialEntries={entries} permissions={context.permissions} />;
}
