# Profile Image API Documentation

## Overview
This API provides functionality for users to upload, retrieve, and delete their profile images. Profile images are stored as base64 strings in the database.

## Base URL
```
http://localhost:3000/api/users
```

## Authentication
All endpoints require authentication. Include the JWT token in the Authorization header:
```
Authorization: Bearer <your-jwt-token>
```

## Endpoints

### 1. Upload Profile Image
**POST** `/profile-image`

Upload a new profile image or update an existing one.

#### Request Body
```json
{
  "profileImage": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="
}
```

#### Request Parameters
- `profileImage` (string, required): Base64 encoded image data with data URI prefix
  - Supported formats: PNG, JPG, JPEG, GIF, WEBP
  - Maximum size: 5MB
  - Format: `data:image/<format>;base64,<base64-data>`

#### Success Response (200)
```json
{
  "success": true,
  "message": "Profile image uploaded successfully",
  "data": {
    "profileImage": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="
  }
}
```

#### Error Responses
- **400 Bad Request**: Invalid image format or size
- **404 Not Found**: User not found
- **500 Internal Server Error**: Server error

### 2. Update Profile Image
**PUT** `/profile-image`

Update an existing profile image. This endpoint requires that the user already has a profile image.

#### Request Body
```json
{
  "profileImage": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="
}
```

#### Request Parameters
- `profileImage` (string, required): Base64 encoded image data with data URI prefix
  - Supported formats: PNG, JPG, JPEG, GIF, WEBP
  - Maximum size: 5MB
  - Format: `data:image/<format>;base64,<base64-data>`

#### Success Response (200)
```json
{
  "success": true,
  "message": "Profile image updated successfully",
  "data": {
    "profileImage": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="
  }
}
```

#### Error Responses
- **400 Bad Request**: Invalid image format, size, or no existing profile image
- **404 Not Found**: User not found
- **500 Internal Server Error**: Server error

### 3. Get Profile Image
**GET** `/profile-image`

Retrieve the user's current profile image.

#### Success Response (200)
```json
{
  "success": true,
  "message": "Profile image retrieved successfully",
  "data": {
    "profileImage": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==",
    "hasProfileImage": true
  }
}
```

#### Response when no image exists
```json
{
  "success": true,
  "message": "Profile image retrieved successfully",
  "data": {
    "profileImage": null,
    "hasProfileImage": false
  }
}
```

#### Error Responses
- **404 Not Found**: User not found
- **500 Internal Server Error**: Server error

### 4. Delete Profile Image
**DELETE** `/profile-image`

Remove the user's profile image.

#### Success Response (200)
```json
{
  "success": true,
  "message": "Profile image deleted successfully"
}
```

#### Error Responses
- **404 Not Found**: User not found
- **500 Internal Server Error**: Server error

## Usage Examples

### Frontend JavaScript Example

#### Upload Profile Image
```javascript
const uploadProfileImage = async (imageFile) => {
  try {
    // Convert file to base64
    const base64 = await convertToBase64(imageFile);
    
    const response = await fetch('/api/users/profile-image', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify({
        profileImage: base64
      })
    });
    
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error uploading image:', error);
  }
};

const convertToBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
};
```

#### Update Profile Image
```javascript
const updateProfileImage = async (imageFile) => {
  try {
    // Convert file to base64
    const base64 = await convertToBase64(imageFile);
    
    const response = await fetch('/api/users/profile-image', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify({
        profileImage: base64
      })
    });
    
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error updating image:', error);
  }
};
```

#### Get Profile Image
```javascript
const getProfileImage = async () => {
  try {
    const response = await fetch('/api/users/profile-image', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    const data = await response.json();
    if (data.success && data.data.hasProfileImage) {
      // Display the image
      const img = document.createElement('img');
      img.src = data.data.profileImage;
      document.body.appendChild(img);
    }
  } catch (error) {
    console.error('Error getting image:', error);
  }
};
```

#### Delete Profile Image
```javascript
const deleteProfileImage = async () => {
  try {
    const response = await fetch('/api/users/profile-image', {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error deleting image:', error);
  }
};
```

## Database Schema

The `profileImage` field has been added to the User model:

```javascript
profileImage: {
    type: String,
    default: null
}
```

## Validation Rules

1. **Image Format**: Must be a valid base64 image with proper data URI prefix
2. **Supported Formats**: PNG, JPG, JPEG, GIF, WEBP
3. **Size Limit**: Maximum 5MB
4. **Authentication**: All endpoints require valid JWT token

## Error Handling

All endpoints include comprehensive error handling with appropriate HTTP status codes and descriptive error messages.

## Security Considerations

1. **Authentication Required**: All endpoints require valid JWT authentication
2. **Input Validation**: Base64 format and size validation
3. **File Type Validation**: Only image formats are accepted
4. **Size Limits**: 5MB maximum file size to prevent abuse

## Testing

You can test these endpoints using tools like Postman or curl:

```bash
# Upload profile image
curl -X POST http://localhost:3000/api/users/profile-image \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{"profileImage": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="}'

# Update profile image
curl -X PUT http://localhost:3000/api/users/profile-image \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{"profileImage": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="}'

# Get profile image
curl -X GET http://localhost:3000/api/users/profile-image \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

# Delete profile image
curl -X DELETE http://localhost:3000/api/users/profile-image \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```
