import { Suspense } from "react"
import { redirect } from "next/navigation"
import type { Metadata } from "next"
import { getTranslations } from "next-intl/server"

import { getAuthContext } from "@/shared/lib/auth-guard"
import { PermissionDeniedError } from "@/shared/lib/errors"
import { getOnboardingStatus } from "@/modules/onboarding/data-access"
import { OnboardingStepper } from "@/modules/onboarding/components/onboarding-stepper"

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

export default async function OnboardingPage() {
  // P0-3 修复：使用 getAuthContext() 替代直接 import @/auth
  // getAuthContext() 在未认证时抛出 PermissionDeniedError，捕获后重定向到 /login
  let ctx
  try {
    ctx = await getAuthContext()
  } catch (e) {
    if (e instanceof PermissionDeniedError) {
      redirect("/login")
    }
    throw e
  }

  // 数据库是 onboarding 状态的唯一真相源
  // （原 session.user.onboarded 检查冗余，DB 查询更准确）
  const status = await getOnboardingStatus(ctx.userId)
  if (!status.required) {
    redirect("/dashboard")
  }

  return (
    <main className="flex min-h-screen items-center justify-center bg-muted/30 p-4">
      <div className="w-full max-w-2xl rounded-lg border bg-background p-8 shadow-sm">
        {/* useSearchParams 需要 Suspense 边界（P1-1 URL query 持久化步骤） */}
        <Suspense fallback={<OnboardingLoading />}>
          <OnboardingStepper initialStatus={status} />
        </Suspense>
      </div>
    </main>
  )
}

function OnboardingLoading() {
  return (
    <div className="grid gap-6" aria-busy="true" aria-live="polite">
      <div className="grid gap-1.5">
        <div className="h-7 w-40 animate-pulse rounded bg-muted" />
        <div className="h-4 w-64 animate-pulse rounded bg-muted" />
      </div>
      <div className="flex items-center gap-2">
        <div className="h-1 flex-1 rounded bg-muted" />
        <div className="h-1 flex-1 rounded bg-muted" />
        <div className="h-1 flex-1 rounded bg-muted" />
        <div className="h-1 flex-1 rounded bg-muted" />
      </div>
      <div className="grid gap-4">
        <div className="h-10 animate-pulse rounded bg-muted" />
        <div className="h-10 animate-pulse rounded bg-muted" />
        <div className="h-10 animate-pulse rounded bg-muted" />
      </div>
    </div>
  )
}
