/**
 * API Response Utilities
 *
 * Consistent, named response creation for all API handlers — core and modules alike.
 * Using these functions makes intent explicit at every return site.
 *
 * Usage:
 *   import { apiSuccess, apiError } from '../respond.js';
 *
 *   return apiSuccess({ user });
 *   return apiSuccess({ users }, { page, total, totalPages });
 *   return apiError('Not Found', 'User not found');
 */

/**
 * Create a successful API response payload.
 *
 * Returns the payload as-is — no envelope wrapping — so existing frontend
 * consumers remain compatible. The function exists to make success paths
 * explicit and searchable alongside apiError() calls.
 *
 * @param {Object} payload - The data to return to the client
 * @returns {Object}
 */
export function apiSuccess(payload) {
  return payload;
}

/**
 * Create an error API response payload.
 *
 * The `code` field is read by getStatusCode() to derive the HTTP status.
 * Always use one of the recognised codes below — any other value maps to 500.
 *
 * Valid codes → HTTP status:
 *   'Unauthorized'          → 401
 *   'Admin access required' → 403
 *   'Forbidden'             → 403
 *   'Not Found'             → 404
 *   'Bad Request'           → 400
 *   'Too Many Requests'     → 429
 *   'Internal Server Error' → 500
 *
 * @param {string} code    - Machine-readable error code
 * @param {string} message - User-facing message, safe for client exposure
 * @returns {{ error: string, message: string }}
 */
export function apiError(code, message) {
  return { error: code, message };
}

/**
 * Derive an HTTP status code from a response payload.
 * Reads the `error` field set by apiError().
 *
 * @param {Object} response
 * @returns {number}
 */
export function getStatusCode(response) {
  if (response.error) {
    switch (response.error) {
      case 'Unauthorized':
        return 401;
      case 'Forbidden':
      case 'Admin access required':
        return 403;
      case 'Not Found':
        return 404;
      case 'Bad Request':
        return 400;
      case 'Too Many Requests':
        return 429;
      default:
        return 500;
    }
  }
  return 200;
}
