// ============================================================
// Error response helper — log full detail server-side, return
// generic message to client to avoid leaking stack traces and
// internal paths.
// ============================================================

function serverError(res, scope, err, publicMessage) {
  try {
    var logger = require('./logger');
    var msg = err && err.message ? err.message : String(err);
    logger.error('[' + scope + '] ' + msg, err && err.stack ? err.stack : '');
  } catch (e) {}
  return res.status(500).json({ error: publicMessage || 'Request failed. Please try again.' });
}

// ============================================================
// AI gateway URL helper — builds endpoint URLs from
// LITELLM_API_BASE, handling both with and without /v1 suffix.
// Usage: gatewayUrl('/audio/speech') → 'https://gw.example.com/v1/audio/speech'
// The OpenAI SDK (ai.js) uses LITELLM_API_BASE directly as
// baseURL and must NOT use this helper.
// ============================================================

function gatewayUrl(path) {
  var base = (process.env.LITELLM_API_BASE || '').replace(/\/+$/, '').replace(/\/v1\/?$/, '');
  return base + '/v1' + (path.startsWith('/') ? path : '/' + path);
}

module.exports = { serverError: serverError, gatewayUrl: gatewayUrl };
