import type { Metadata } from "next"
import type { JSX } from "react"
import { notFound } from "next/navigation"
import { getTranslations } from "next-intl/server"

import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { SectionErrorBoundary } from "@/shared/components/section-error-boundary"
import { getClassNamesByIds } from "@/modules/classes/data-access"

import { MessageGroupCompose } from "@/modules/messaging/components/message-group-compose"

export const dynamic = "force-dynamic"

export async function generateMetadata(): Promise<Metadata> {
  const t = await getTranslations("messages")
  return {
    title: t("title.groupCompose"),
    description: t("description.groupCompose"),
  }
}

export default async function GroupComposeMessagePage(): Promise<JSX.Element> {
  const ctx = await requirePermission(Permissions.MESSAGE_SEND)
  const t = await getTranslations("messages")

  // P2-2: 群发仅限教师（class_taught DataScope）；其他角色无权访问此页面
  if (ctx.dataScope.type !== "class_taught") {
    notFound()
  }

  const classIds = ctx.dataScope.classIds
  const classNameMap = await getClassNamesByIds(classIds)
  const classOptions = classIds.map((id) => ({
    id,
    name: classNameMap.get(id) ?? id,
  }))

  return (
    <div className="flex h-full flex-col p-8">
      <div className="mx-auto w-full max-w-3xl space-y-6">
        <div>
          <h2 className="text-2xl font-bold tracking-tight">{t("title.groupCompose")}</h2>
          <p className="text-muted-foreground">{t("description.groupCompose")}</p>
        </div>
        <SectionErrorBoundary namespace="messages">
          <MessageGroupCompose classOptions={classOptions} />
        </SectionErrorBoundary>
      </div>
    </div>
  )
}
