"use client"

import type { ActionState } from "@/shared/types/action-state"

/**
 * 根据 ActionState 的 errorCode 解析本地化错误消息。
 *
 * 优先级：
 * 1. errorCode 以 `invalid_date:` 开头 → 查 `errors.invalid_{field}` i18n 键
 * 2. errorCode 匹配已知通用码（unexpected/validation_error/not_found/permission_denied）→ 查对应 i18n 键
 * 3. 回退到 result.message
 * 4. 最终回退到 fallback
 *
 * @example
 * ```tsx
 * const t = useTranslations("attendance")
 * const msg = resolveActionError(result, t, t("errors.unexpected"))
 * toast.error(msg)
 * ```
 */
export function resolveActionError<T>(
  result: ActionState<T> | null,
  t: (key: string) => string,
  fallback: string
): string {
  if (!result) return fallback

  const code = result.errorCode

  // 日期格式错误：invalid_date:date / invalid_date:startDate / invalid_date:endDate
  if (code?.startsWith("invalid_date:")) {
    const field = code.split(":")[1]
    const key = `errors.invalid_${field}`
    try {
      const translated = t(key)
      if (translated && translated !== key) return translated
    } catch {
      // 键不存在，回退
    }
  }

  // 通用错误码映射
  const codeMap: Record<string, string> = {
    unexpected: "errors.unexpected",
    validation_error: "errors.invalidForm",
    not_found: "errors.notFound",
    permission_denied: "errors.insufficientPermissions",
  }

  if (code && codeMap[code]) {
    try {
      const translated = t(codeMap[code])
      if (translated && translated !== codeMap[code]) return translated
    } catch {
      // 键不存在，回退
    }
  }

  return result.message || fallback
}
