import { redirect } from "next/navigation";

import { getCurrentAuthContext } from "@/modules/core/server/auth";
import { hasPermission } from "@/modules/core/server/permissions";
import { NoticesWorkspaceClient } from "@/modules/notices/components/NoticesWorkspaceClient";
import { listNoticeCenterData } from "@/modules/notices/server/operations";
import { getWorkspaceHref } from "@/modules/shared/lib/workspace-routing";

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

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

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

  const data = await listNoticeCenterData(organizationId, context.account.id);
  return <NoticesWorkspaceClient canManage={hasPermission(context.permissions, "notice:manage")} initialData={data} />;
}
