# Career Guidance WebSocket API Documentation

## Overview
This API provides real-time career guidance through WebSocket connections and REST endpoints for management and testing.

## WebSocket Connection

### Connection URL
```
ws://localhost:3000/ws/career-guidance?token=YOUR_JWT_TOKEN
```

### Authentication
- JWT token required in query parameter or Authorization header
- Token must be valid and not expired

### Message Format

#### Client to Server Messages

**Career Guidance Request:**
```json
{
  "type": "career_guidance",
  "userId": "user_id_here",
  "occupation": "software engineer"
}
```

**Ping Message:**
```json
{
  "type": "ping"
}
```

#### Server to Client Messages

**Connection Confirmation:**
```json
{
  "type": "connection",
  "message": "Connected to Career Guidance Server...",
  "clientId": "career_client_abc123",
  "user": {
    "id": "user_id",
    "email": "user@example.com",
    "name": "User Name"
  }
}
```

**Processing Indicator:**
```json
{
  "type": "processing",
  "message": "Analyzing your career profile and generating personalized guidance..."
}
```

**Career Guidance Response:**
```json
{
  "type": "career_guidance_response",
  "data": {
    "user": {
      "id": "user_id",
      "name": "User Name",
      "email": "user@example.com"
    },
    "currentOccupation": "software engineer",
    "relatedOccupations": [
      "Senior Software Engineer",
      "Tech Lead",
      "Software Architect",
      "DevOps Engineer",
      "Full Stack Developer",
      "Mobile App Developer",
      "Data Engineer"
    ],
    "recommendedCertifications": [
      {
        "name": "AWS Certified Solutions Architect",
        "provider": "Amazon Web Services",
        "duration": "3 months"
      },
      {
        "name": "Google Cloud Professional Developer",
        "provider": "Google Cloud",
        "duration": "2 months"
      }
    ],
    "industrialSwitchingOpportunities": [
      {
        "industry": "FinTech",
        "roles": ["FinTech Developer", "Blockchain Developer", "Payment Systems Engineer"]
      },
      {
        "industry": "Healthcare Tech",
        "roles": ["HealthTech Developer", "Medical Software Engineer", "Telemedicine Developer"]
      }
    ],
    "skillsAssessment": {
      "currentSkills": ["Programming", "Problem Solving", "System Design", "Database Management"],
      "recommendedSkills": ["Cloud Computing", "DevOps", "Machine Learning", "Microservices", "Security"]
    },
    "careerProgressionRoadmap": [
      {
        "level": "Entry Level (0-2 years)",
        "roles": ["Junior Developer", "Software Engineer I"],
        "skills": ["Basic Programming", "Version Control", "Testing"]
      },
      {
        "level": "Mid Level (2-5 years)",
        "roles": ["Software Engineer II", "Senior Developer"],
        "skills": ["System Design", "Code Review", "Mentoring"]
      },
      {
        "level": "Senior Level (5-8 years)",
        "roles": ["Senior Software Engineer", "Tech Lead"],
        "skills": ["Architecture", "Team Leadership", "Strategic Planning"]
      },
      {
        "level": "Expert Level (8+ years)",
        "roles": ["Principal Engineer", "Engineering Manager", "CTO"],
        "skills": ["Technical Strategy", "Team Management", "Business Acumen"]
      }
    ],
    "generatedAt": "2024-01-15T10:30:00.000Z"
  },
  "timestamp": "2024-01-15T10:30:00.000Z"
}
```

**Error Response:**
```json
{
  "type": "error",
  "message": "Error description",
  "timestamp": "2024-01-15T10:30:00.000Z"
}
```

**Pong Response:**
```json
{
  "type": "pong",
  "timestamp": 1705312200000
}
```

## REST API Endpoints

### Base URL
```
http://localhost:3000/api/career-guidance
```

### Endpoints

#### 1. Health Check
**GET** `/health`

Check if the Career Guidance WebSocket server is running.

**Response:**
```json
{
  "success": true,
  "message": "Career Guidance WebSocket server is running",
  "status": "online",
  "stats": {
    "totalConnections": 150,
    "activeConnections": 25,
    "currentClients": 25,
    "totalMessages": 1250,
    "errors": 5
  },
  "timestamp": "2024-01-15T10:30:00.000Z"
}
```

#### 2. Get Connected Clients
**GET** `/clients`
**Headers:** `Authorization: Bearer YOUR_JWT_TOKEN`

Get information about all connected clients.

**Response:**
```json
{
  "success": true,
  "message": "Connected clients retrieved successfully",
  "clients": [
    {
      "id": "career_client_abc123",
      "connectedAt": "2024-01-15T10:25:00.000Z",
      "user": {
        "id": "user_id",
        "email": "user@example.com",
        "name": "User Name"
      }
    }
  ],
  "totalClients": 1,
  "timestamp": "2024-01-15T10:30:00.000Z"
}
```

#### 3. Broadcast Message
**POST** `/broadcast`
**Headers:** `Authorization: Bearer YOUR_JWT_TOKEN`

Send a message to all connected clients.

**Request Body:**
```json
{
  "message": "Server maintenance scheduled for tonight",
  "type": "announcement"
}
```

**Response:**
```json
{
  "success": true,
  "message": "Broadcast message sent successfully",
  "broadcastMessage": {
    "type": "announcement",
    "message": "Server maintenance scheduled for tonight",
    "timestamp": "2024-01-15T10:30:00.000Z",
    "from": "admin"
  }
}
```

#### 4. Get Server Statistics
**GET** `/stats`
**Headers:** `Authorization: Bearer YOUR_JWT_TOKEN`

Get detailed server statistics.

**Response:**
```json
{
  "success": true,
  "message": "Statistics retrieved successfully",
  "stats": {
    "totalConnections": 150,
    "activeConnections": 25,
    "currentClients": 25,
    "totalMessages": 1250,
    "errors": 5,
    "uptime": 3600,
    "memoryUsage": {
      "rss": 45678912,
      "heapTotal": 20971520,
      "heapUsed": 15728640,
      "external": 1234567
    }
  },
  "timestamp": "2024-01-15T10:30:00.000Z"
}
```

#### 5. Test Career Guidance
**POST** `/test-guidance`
**Headers:** `Authorization: Bearer YOUR_JWT_TOKEN`

Test career guidance generation without WebSocket connection.

**Request Body:**
```json
{
  "userId": "user_id_here",
  "occupation": "software engineer"
}
```

**Response:**
```json
{
  "success": true,
  "message": "Career guidance generated successfully",
  "data": {
    "user": {
      "id": "user_id",
      "name": "User Name",
      "email": "user@example.com"
    },
    "currentOccupation": "software engineer",
    "relatedOccupations": [...],
    "recommendedCertifications": [...],
    "industrialSwitchingOpportunities": [...],
    "skillsAssessment": {...},
    "careerProgressionRoadmap": [...],
    "generatedAt": "2024-01-15T10:30:00.000Z"
  },
  "timestamp": "2024-01-15T10:30:00.000Z"
}
```

#### 6. Get Connection Information
**GET** `/connection-info`

Get WebSocket connection information and requirements.

**Response:**
```json
{
  "success": true,
  "message": "WebSocket connection information",
  "connectionInfo": {
    "serverPath": "/ws/career-guidance",
    "supportedMessageTypes": ["career_guidance", "ping"],
    "authentication": "JWT token required",
    "maxPayload": "16MB",
    "compression": "disabled"
  },
  "timestamp": "2024-01-15T10:30:00.000Z"
}
```

## Error Responses

All endpoints return consistent error responses:

```json
{
  "success": false,
  "message": "Error description",
  "error": "Detailed error message"
}
```

## Usage Examples

### JavaScript WebSocket Client
```javascript
const token = 'your_jwt_token_here';
const ws = new WebSocket(`ws://localhost:3000/ws/career-guidance?token=${token}`);

ws.onopen = function() {
    console.log('Connected to Career Guidance WebSocket');
    
    // Send career guidance request
    ws.send(JSON.stringify({
        type: 'career_guidance',
        userId: 'user123',
        occupation: 'software engineer'
    }));
};

ws.onmessage = function(event) {
    const data = JSON.parse(event.data);
    console.log('Received:', data);
    
    if (data.type === 'career_guidance_response') {
        console.log('Career Guidance:', data.data);
    }
};

ws.onerror = function(error) {
    console.error('WebSocket error:', error);
};

ws.onclose = function() {
    console.log('WebSocket connection closed');
};
```

### cURL Examples

**Health Check:**
```bash
curl -X GET http://localhost:3000/api/career-guidance/health
```

**Get Statistics:**
```bash
curl -X GET http://localhost:3000/api/career-guidance/stats \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

**Test Career Guidance:**
```bash
curl -X POST http://localhost:3000/api/career-guidance/test-guidance \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "userId": "user123",
    "occupation": "software engineer"
  }'
```

## Server Setup

To use this WebSocket server, you need to initialize it in your main server file:

```javascript
const express = require('express');
const http = require('http');
const careerGuidanceRoutes = require('./routes/careerGuidanceRoutes');

const app = express();
const server = http.createServer(app);

// Initialize Career Guidance WebSocket
const careerGuidanceWS = careerGuidanceRoutes.initializeCareerGuidanceWS(server);

// Use the routes
app.use('/api/career-guidance', careerGuidanceRoutes);

server.listen(3000, () => {
    console.log('Server running on port 3000');
});
```

## Supported Occupations

The system currently supports career guidance for:
- Software Engineer
- Teacher
- Doctor
- Business Analyst
- And generic fallback for other occupations

Each occupation gets personalized:
- Related job roles
- Recommended certifications
- Industry switching opportunities
- Skills assessment
- Career progression roadmap
