import { redirect } from "next/navigation"
import { getTranslations } from "next-intl/server"
import { headers } from "next/headers"

import { requireAuth } from "@/shared/lib/auth-guard"
import { SettingsView } from "@/modules/settings/components/settings-view"
import { SettingsServiceProvider } from "@/modules/settings/components/settings-service-context"
import { resolveRoleSettingsConfig } from "@/modules/settings/config/role-settings-config"
import type { SettingsService } from "@/modules/settings/types"
import {
  updateProfileAction,
  updateNotificationPreferencesAction,
} from "@/modules/settings/actions-service"
import { getUserProfile } from "@/modules/users/data-access"
import { getNotificationPreferences } from "@/modules/notifications/preferences"

export const dynamic = "force-dynamic"

export async function generateMetadata() {
  const t = await getTranslations("settings")
  return { title: t("title") }
}

export default async function SettingsPage() {
  const ctx = await requireAuth()

  const userId = ctx.userId
  const userProfile = await getUserProfile(userId)

  if (!userProfile) redirect("/login")

  const roles = ctx.roles
  const notificationPrefs = await getNotificationPreferences(userId)
  const t = await getTranslations("settings")

  // 获取当前请求的 User-Agent，用于安全中心标记当前会话
  const headerList = await headers()
  const currentUserAgent = headerList.get("user-agent") ?? ""

  const config = resolveRoleSettingsConfig(roles)
  const description = t(config?.descriptionKey ?? "title")
  const backHref = config?.backHref ?? "/dashboard"
  const generalExtra = config?.generalExtra

  // 构建 SettingsService：仅传递 Server Action 引用
  // （Next.js 要求传递给 Client Component 的函数必须是 "use server" 标记的 Server Action）
  const service: SettingsService = {
    profile: {
      updateProfile: updateProfileAction,
    },
    notifications: {
      updatePreferences: updateNotificationPreferencesAction,
    },
  }

  return (
    <SettingsServiceProvider service={service}>
      <SettingsView
        description={description}
        backHref={backHref}
        user={userProfile}
        notificationPreferences={notificationPrefs}
        generalExtra={generalExtra}
        currentUserAgent={currentUserAgent}
      />
    </SettingsServiceProvider>
  )
}
