/**
 * Response Formatter Middleware
 * Intercepts all responses and converts them to unified format: { code: 0, message: "", data: {} }
 */

/**
 * Override res.json to automatically format responses
 */
const responseFormatter = (req, res, next) => {
  const originalJson = res.json.bind(res);

  res.json = function(body) {
    // If response already has the new format (has 'code' field), don't transform
    if (body && typeof body.code === 'number') {
      return originalJson(body);
    }

    // Transform old format to new format
    if (body && typeof body === 'object') {
      // Success response: { success: true, data: {...}, pagination: {...} }
      if (body.success === true) {
        const response = {
          code: 0,
          message: body.message || 'Success',
          data: body.data || null,
        };
        // Preserve pagination if present
        if (body.pagination) {
          response.pagination = body.pagination;
        }
        return originalJson(response);
      }

      // Error response: { success: false, error: {...} }
      if (body.success === false) {
        const statusCode = res.statusCode || 400;
        return originalJson({
          code: statusCode,
          message: body.error?.message || body.message || 'Error',
          data: null,
          ...(process.env.NODE_ENV === 'development' && body.error && {
            error: body.error
          }),
        });
      }

      // Direct data response (no success field)
      // Assume it's successful data
      return originalJson({
        code: 0,
        message: 'Success',
        data: body,
      });
    }

    // For other types, wrap in standard format
    return originalJson({
      code: 0,
      message: 'Success',
      data: body,
    });
  };

  next();
};

module.exports = responseFormatter;
