import { isString } from "es-toolkit";

import type { CheckFailure } from "../types";

export function errorFailure(phase: CheckFailure["phase"], path: string, message: string): CheckFailure {
  return {
    kind: "error",
    message,
    path,
    phase,
  };
}

export function mismatchFailure(
  phase: CheckFailure["phase"],
  path: string,
  expected: unknown,
  actual: unknown,
  message: string,
): CheckFailure {
  return {
    actual: truncateActual(actual),
    expected,
    kind: "mismatch",
    message,
    path,
    phase,
  };
}

export function truncateActual(value: unknown, maxLen = 200): unknown {
  if (value === undefined || value === null) return value;

  const str = isString(value) ? value : typeof value === "object" && value !== null ? JSON.stringify(value) : undefined;
  if (str === undefined) return value;
  if (str.length <= maxLen) return value;
  return `${str.slice(0, maxLen)}…(共 ${str.length} 字符)`;
}
