# Profile Image API Documentation

## Overview
This API provides comprehensive profile image management functionality including file upload with compression, retrieval, and deletion. Images are stored as files (not base64) and compressed to under 100KB for optimal performance.

## File Storage Details
- **Storage Location**: `uploads/profiles/` directory
- **File Naming**: `profile_{timestamp}_{randomString}.jpg`
- **Compression**: Automatic compression to under 100KB
- **Supported Formats**: JPEG, PNG, WebP (all converted to JPEG)
- **Max Upload Size**: 10MB (before compression)
- **Final Size**: Under 100KB after compression

## API Endpoints

### 1. Upload Profile Image
**POST** `/api/users/profile-image/:userId`

Upload a new profile image with automatic compression.

#### Parameters
- `userId` (path): The user ID to upload profile image for
- `profileImage` (file): The image file to upload

#### Authentication
Requires valid JWT token in Authorization header.

#### Request
```javascript
// Using FormData
const formData = new FormData();
formData.append('profileImage', fileInput.files[0]);

fetch('/api/users/profile-image/userId123', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer your_jwt_token'
  },
  body: formData
});
```

#### Response
```javascript
{
  "success": true,
  "message": "Profile image uploaded successfully",
  "data": {
    "userId": "userId123",
    "name": "User Name",
    "profileImage": "uploads/profiles/profile_1234567890_abc123.jpg",
    "profileImageUrl": "/uploads/profiles/profile_1234567890_abc123.jpg",
    "imageDetails": {
      "filename": "profile_1234567890_abc123.jpg",
      "originalSize": "2.5 MB",
      "compressedSize": "85.2 KB",
      "compressionRatio": "96.7%"
    }
  }
}
```

### 2. Get Profile Image
**GET** `/api/users/profile-image/:userId`

Get the profile image information for a user.

#### Parameters
- `userId` (path): The user ID to get profile image for

#### Response
```javascript
{
  "success": true,
  "message": "Profile image retrieved successfully",
  "data": {
    "userId": "userId123",
    "name": "User Name",
    "profileImage": "uploads/profiles/profile_1234567890_abc123.jpg",
    "profileImageUrl": "/uploads/profiles/profile_1234567890_abc123.jpg"
  }
}
```

### 3. Update Profile Image
**PUT** `/api/users/profile-image/:userId`

Update/replace an existing profile image (same as upload).

#### Parameters
- `userId` (path): The user ID to update profile image for
- `profileImage` (file): The new image file

#### Response
Same as upload response.

### 4. Delete Profile Image
**DELETE** `/api/users/profile-image/:userId`

Delete a user's profile image.

#### Parameters
- `userId` (path): The user ID to delete profile image for

#### Response
```javascript
{
  "success": true,
  "message": "Profile image deleted successfully",
  "data": {
    "userId": "userId123",
    "name": "User Name",
    "profileImage": null,
    "deletedImagePath": "uploads/profiles/profile_1234567890_abc123.jpg"
  }
}
```

### 5. Serve Profile Image
**GET** `/uploads/profiles/:filename`

Serve profile image files directly (public endpoint).

#### Parameters
- `filename` (path): The profile image filename

#### Response
Returns the image file with appropriate headers and caching.

## Compression Details

### Compression Algorithm
1. **Resize**: Images are resized to fit within 800x800 pixels (maintaining aspect ratio)
2. **Quality Adjustment**: JPEG quality is adjusted from 85% down to 10% until target size is reached
3. **Format Conversion**: All images are converted to JPEG format
4. **Progressive Encoding**: Uses progressive JPEG for better loading experience

### Compression Logs
```
🖼️ [PROFILE IMAGE COMPRESSION DEBUG] Starting compression for: profile.jpg
🖼️ [PROFILE IMAGE COMPRESSION DEBUG] Original image size: 2500.00 KB
🖼️ [PROFILE IMAGE COMPRESSION DEBUG] Target size: 100 KB
🖼️ [PROFILE IMAGE COMPRESSION DEBUG] Original dimensions: 2048x1536
🖼️ [PROFILE IMAGE COMPRESSION DEBUG] Image format: jpeg
🖼️ [PROFILE IMAGE COMPRESSION DEBUG] Quality 85: 450.25 KB
🖼️ [PROFILE IMAGE COMPRESSION DEBUG] Quality 75: 320.15 KB
🖼️ [PROFILE IMAGE COMPRESSION DEBUG] Quality 65: 280.45 KB
🖼️ [PROFILE IMAGE COMPRESSION DEBUG] Quality 55: 95.80 KB
✅ [PROFILE IMAGE COMPRESSION DEBUG] Final size: 95.80 KB
✅ [PROFILE IMAGE COMPRESSION DEBUG] Compression ratio: 96.2%
```

## Error Responses

### Common Errors
```javascript
// No file uploaded
{
  "success": false,
  "message": "No profile image file uploaded"
}

// Invalid file type
{
  "success": false,
  "message": "Invalid file type. Only JPEG, PNG, and WebP images are allowed"
}

// File too large
{
  "success": false,
  "message": "File too large. Maximum size is 10MB"
}

// User not found
{
  "success": false,
  "message": "User not found"
}

// Server error
{
  "success": false,
  "message": "Failed to upload profile image",
  "error": "Detailed error message"
}
```

## Usage Examples

### JavaScript/Fetch
```javascript
// Upload profile image
const uploadProfileImage = async (userId, file) => {
  const formData = new FormData();
  formData.append('profileImage', file);
  
  const response = await fetch(`/api/users/profile-image/${userId}`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`
    },
    body: formData
  });
  
  return await response.json();
};

// Get profile image
const getProfileImage = async (userId) => {
  const response = await fetch(`/api/users/profile-image/${userId}`, {
    headers: {
      'Authorization': `Bearer ${token}`
    }
  });
  
  return await response.json();
};

// Delete profile image
const deleteProfileImage = async (userId) => {
  const response = await fetch(`/api/users/profile-image/${userId}`, {
    method: 'DELETE',
    headers: {
      'Authorization': `Bearer ${token}`
    }
  });
  
  return await response.json();
};
```

### cURL Examples
```bash
# Upload profile image
curl -X POST \
  -H "Authorization: Bearer your_jwt_token" \
  -F "profileImage=@/path/to/image.jpg" \
  "http://localhost:5500/api/users/profile-image/userId123"

# Get profile image info
curl -H "Authorization: Bearer your_jwt_token" \
  "http://localhost:5500/api/users/profile-image/userId123"

# Delete profile image
curl -X DELETE \
  -H "Authorization: Bearer your_jwt_token" \
  "http://localhost:5500/api/users/profile-image/userId123"

# Access profile image directly
curl "http://localhost:5500/uploads/profiles/profile_1234567890_abc123.jpg"
```

### HTML Form Example
```html
<form id="profileImageForm" enctype="multipart/form-data">
  <input type="file" name="profileImage" accept="image/*" required>
  <button type="submit">Upload Profile Image</button>
</form>

<script>
document.getElementById('profileImageForm').addEventListener('submit', async (e) => {
  e.preventDefault();
  
  const formData = new FormData(e.target);
  
  try {
    const response = await fetch('/api/users/profile-image/userId123', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer your_jwt_token'
      },
      body: formData
    });
    
    const result = await response.json();
    console.log('Upload result:', result);
  } catch (error) {
    console.error('Upload error:', error);
  }
});
</script>
```

## Database Schema

### User Model Update
```javascript
{
  profileImage: {
    type: String,
    default: null,
    // Stores the file path to the profile image (e.g., "uploads/profiles/profile_1234567890_abc123.jpg")
    // Not base64 data anymore
  }
}
```

## Features

### File Management
- **Automatic Cleanup**: Old profile images are deleted when new ones are uploaded
- **Unique Naming**: Each image gets a unique filename to prevent conflicts
- **Directory Creation**: Profile images directory is created automatically
- **File Validation**: Strict file type and size validation

### Performance Optimizations
- **Compression**: All images compressed to under 100KB
- **Caching**: Images served with 1-year cache headers
- **Progressive JPEG**: Better loading experience
- **Memory Storage**: Multer uses memory storage for processing

### Security Features
- **Authentication Required**: All endpoints require valid JWT tokens
- **File Type Validation**: Only image files allowed
- **Size Limits**: 10MB upload limit, 100KB final size
- **Path Validation**: Secure file path handling

## Migration from Base64

### Before (Base64)
```javascript
{
  profileImage: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD..." // Large base64 string
}
```

### After (File Path)
```javascript
{
  profileImage: "uploads/profiles/profile_1234567890_abc123.jpg" // File path
}
```

### Benefits of File Storage
1. **Reduced Database Size**: No more large base64 strings in database
2. **Better Performance**: Faster database queries and API responses
3. **Efficient Caching**: Browser caching works properly with file URLs
4. **CDN Ready**: Easy to integrate with CDNs
5. **Compression**: Automatic image optimization
6. **Scalability**: Better for handling large numbers of users

## Integration Notes

1. **Frontend Changes**: Update frontend to use file URLs instead of base64 data
2. **Image Display**: Use the `profileImageUrl` field to display images
3. **File Upload**: Use FormData for file uploads, not JSON
4. **Error Handling**: Handle file upload errors appropriately
5. **Loading States**: Show loading indicators during upload and compression

## Troubleshooting

### Common Issues
1. **File Not Found**: Check if the file exists in the uploads/profiles directory
2. **Permission Errors**: Ensure the uploads directory has write permissions
3. **Memory Issues**: Large files might cause memory issues during compression
4. **CORS Issues**: Ensure proper CORS configuration for file uploads

### Debug Logs
The API provides comprehensive debug logging for all operations:
- Upload progress and compression details
- File serving logs
- Error details with stack traces
- Performance metrics (compression ratios, file sizes)
