/**
 * MySQL JSON columns + mysql2/Sequelize (especially under Next.js) often
 * come back as strings instead of parsed objects. Ratings then look empty
 * (`Number('{"score":5}') === NaN`) and choices render as raw JSON.
 */
export function parseJsonValue(value: unknown): unknown {
  if (value == null) return null;

  let current: unknown = value;

  if (typeof Buffer !== "undefined" && Buffer.isBuffer(current)) {
    current = current.toString("utf8");
  }

  for (let i = 0; i < 2 && typeof current === "string"; i++) {
    const trimmed = current.trim();
    if (!trimmed) return current;
    if (trimmed === "null") return null;

    const looksLikeJson =
      (trimmed.startsWith("{") && trimmed.endsWith("}")) ||
      (trimmed.startsWith("[") && trimmed.endsWith("]")) ||
      (trimmed.startsWith('"') && trimmed.endsWith('"'));

    if (!looksLikeJson) return current;

    try {
      current = JSON.parse(trimmed);
    } catch {
      return current;
    }
  }

  return current;
}

export function parseJsonColumn<T extends object>(value: unknown): T | null {
  const parsed = parseJsonValue(value);
  if (parsed == null || typeof parsed !== "object") return null;
  return parsed as T;
}
