import { ApiError } from "./api_result";

export const CHARACTER_ERROR_CODES = [
  "CHARACTER_DISABLED",
  "CHARACTER_NOT_FOUND",
  "CHARACTER_MISMATCH",
  "CHARACTER_STATE_UNAVAILABLE",
] as const;

export type CharacterErrorCode = (typeof CHARACTER_ERROR_CODES)[number];

export function getCharacterErrorCode(error: unknown): CharacterErrorCode | null {
  let current = error;
  for (let depth = 0; depth < 5 && current; depth += 1) {
    if (current instanceof ApiError) {
      const code = readErrorCode(current.details);
      if (isCharacterErrorCode(code)) return code;
    }
    current = current instanceof Error ? current.cause : null;
  }
  return null;
}

function readErrorCode(value: unknown): unknown {
  if (!value || typeof value !== "object") return null;
  const data = value as Record<string, unknown>;
  if (typeof data.errorCode === "string") return data.errorCode;
  return readErrorCode(data.detail) ?? readErrorCode(data.data);
}

function isCharacterErrorCode(value: unknown): value is CharacterErrorCode {
  return (
    typeof value === "string" &&
    (CHARACTER_ERROR_CODES as readonly string[]).includes(value)
  );
}
