"use server"

import { cookies } from "next/headers"
import { revalidatePath } from "next/cache"

import {
  LOCALE_COOKIE,
  LOCALE_COOKIE_OPTIONS,
  type Locale,
  isLocale,
} from "@/shared/i18n/locale"

/**
 * 切换语言：写入 cookie + 触发页面刷新。
 *
 * 设计说明：
 * - 不使用 URL 路由段，避免破坏现有路由组结构
 * - cookie 持久化用户偏好，SSR 时由 i18n/request.ts 读取
 * - revalidatePath 确保所有页面用新 locale 重新渲染
 */
export async function setLocaleAction(locale: string): Promise<{ success: boolean }> {
  if (!isLocale(locale)) {
    return { success: false }
  }

  const cookieStore = await cookies()
  cookieStore.set(LOCALE_COOKIE, locale as Locale, LOCALE_COOKIE_OPTIONS)

  // 刷新所有页面，让 SSR 用新 locale 重新渲染
  revalidatePath("/", "layout")
  return { success: true }
}
