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

import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getAnnouncementByIdForUser } from "@/modules/announcements/data-access"
import { AnnouncementDetail } from "@/modules/announcements/components/announcement-detail"
import { AnnouncementsServiceProvider } from "@/modules/announcements/components/announcements-service-context"

export const dynamic = "force-dynamic"

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

export default async function AnnouncementDetailPage({
  params,
}: {
  params: Promise<{ id: string }>
}): Promise<JSX.Element> {
  const { id } = await params
  const ctx = await requirePermission(Permissions.ANNOUNCEMENT_READ)

  // P0-1 修复：在 data-access 层结合受众与 status 过滤，避免越权读取草稿/归档/他人班级公告。
  // 不可见时统一返回 404，不暴露公告存在性。
  const announcement = await getAnnouncementByIdForUser(id, ctx.userId, ctx.dataScope)
  if (!announcement) notFound()

  return (
    <AnnouncementsServiceProvider>
      <div className="flex h-full flex-col space-y-8 p-8">
        <AnnouncementDetail
          announcement={announcement}
          canManage={false}
          backHref="/announcements"
        />
      </div>
    </AnnouncementsServiceProvider>
  )
}
