/**
 * Adaptive Practice 模块错误类型。
 *
 * 用结构化错误码替代硬编码中文 message，
 * 前端通过 errorCode 查 i18n 翻译键展示。
 *
 * 继承 BusinessError，使 handleActionError 能自动保留 errorCode。
 */

import { BusinessError } from "@/shared/lib/action-utils"

export const PRACTICE_ERROR_CODES = [
  "session_not_found",
  "session_ended",
  "answer_not_found",
  "answer_already_submitted",
  "question_not_found",
  "session_not_complete",
  "no_questions_found",
  "forbidden",
] as const

export type PracticeErrorCode = (typeof PRACTICE_ERROR_CODES)[number]

/**
 * 业务错误：携带 errorCode 的错误类。
 *
 * 用于 data-access 层抛错，actions 层通过 handleActionError 捕获后
 * 转换为 ActionState.errorCode 返回前端，前端 t(`errors.${errorCode}`) 查翻译。
 */
export class PracticeError extends BusinessError {
  readonly code: PracticeErrorCode

  constructor(code: PracticeErrorCode) {
    // message 留空，前端通过 errorCode 查 i18n 文案
    super(code, code)
    this.name = "PracticeError"
    this.code = code
  }
}

export function isPracticeError(e: unknown): e is PracticeError {
  return e instanceof PracticeError
}

/**
 * 便捷工厂函数。
 */
export const practiceErrors = {
  sessionNotFound: () => new PracticeError("session_not_found"),
  sessionEnded: () => new PracticeError("session_ended"),
  answerNotFound: () => new PracticeError("answer_not_found"),
  answerAlreadySubmitted: () => new PracticeError("answer_already_submitted"),
  questionNotFound: () => new PracticeError("question_not_found"),
  sessionNotComplete: () => new PracticeError("session_not_complete"),
  noQuestionsFound: () => new PracticeError("no_questions_found"),
  forbidden: () => new PracticeError("forbidden"),
}
