/**
 * Log API failures to the browser console with full server payload (detail, traceback).
 * Used by setup wizard and other pages that use raw fetch().
 */
(function (global) {
  global.CNPERP = global.CNPERP || {};

  function formatMessage(data, fallback) {
    if (!data || typeof data !== 'object') {
      return fallback || 'Request failed';
    }
    const parts = [];
    if (data.message && data.message !== 'An internal error occurred') {
      parts.push(String(data.message));
    }
    if (data.detail) {
      const d =
        typeof data.detail === 'string'
          ? data.detail
          : Array.isArray(data.detail)
            ? data.detail.map((e) => e.msg || e.loc?.join('.') + ': ' + e.msg || JSON.stringify(e)).join('; ')
            : JSON.stringify(data.detail);
      if (d && !parts.includes(d)) parts.push(d);
    }
    if (data.error && typeof data.error === 'string' && data.error !== 'http_error') {
      parts.push(`[${data.error}]`);
    }
    if (!parts.length && data.message) {
      parts.push(String(data.message));
    }
    return parts.join(' — ') || fallback || 'Request failed';
  }

  /**
   * @param {string} label - Short context, e.g. "Setup register-full"
   * @param {Response} response
   * @param {object|null} data - Parsed JSON body
   */
  function logError(label, response, data) {
    const status = response?.status ?? '?';
    const url = response?.url ?? '';
    console.groupCollapsed(`[CNPERP] ${label} — HTTP ${status}`);
    console.error('URL:', url);
    console.error('Response body:', data);
    if (data?.traceback) {
      console.error('Server traceback:\n' + data.traceback);
    }
    console.groupEnd();
    return data;
  }

  CNPERP.formatApiError = formatMessage;
  CNPERP.logApiError = logError;
})(typeof window !== 'undefined' ? window : global);
