import { notFound } from "next/navigation"
import type { Metadata } from "next"
import type { JSX } from "react"
import { Suspense } from "react"
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 { getMessageDetailPageData } from "@/modules/messaging/data-access"
import { MessageDetail } from "@/modules/messaging/components/message-detail"
import { Skeleton } from "@/shared/components/ui/skeleton"

export const dynamic = "force-dynamic"

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

/**
 * P2-9: 消息详情骨架屏。
 */
function MessageDetailSkeleton(): JSX.Element {
  return (
    <div className="space-y-6" role="status" aria-label="Loading message">
      <Skeleton className="h-8 w-3/4" />
      <Skeleton className="h-4 w-1/2" />
      <Skeleton className="h-32 w-full" />
      <div className="space-y-2">
        <Skeleton className="h-4 w-full" />
        <Skeleton className="h-4 w-5/6" />
        <Skeleton className="h-4 w-4/5" />
      </div>
    </div>
  )
}

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

  const message = await getMessageDetailPageData(id, ctx.userId)
  if (!message) notFound()

  return (
    <div className="flex h-full flex-col p-8">
      {/* P2-8 + P2-9: 详情区块 ErrorBoundary 包裹 */}
      <SectionErrorBoundary namespace="messages">
        <Suspense fallback={<MessageDetailSkeleton />}>
          <MessageDetail message={message} currentUserId={ctx.userId} />
        </Suspense>
      </SectionErrorBoundary>
    </div>
  )
}
