# Product Image Upload Feature

## Overview
Basic product image upload functionality has been added to the system. This allows products to have associated images that can be uploaded, updated, and served via the API.

---

## Implementation Details

### 1. Database Schema
- **Field Added**: `image_url` (VARCHAR(255)) to `products` table
- **Type**: Optional field (allowNull: true)
- **Purpose**: Stores the relative path to the uploaded product image

### 2. File Upload Middleware
**File**: `server/middlewares/upload.js`

**Features**:
- Uses `multer` for handling multipart/form-data file uploads
- Stores files in `uploads/products/` directory
- Generates unique filenames: `{sanitized-name}-{timestamp}-{random}.{ext}`
- Validates file types (default: jpeg, png, jpg, gif, webp)
- Enforces file size limit (default: 5MB)
- Handles upload errors gracefully

**Configuration** (via `.env`):
- `MAX_FILE_SIZE`: Maximum file size in bytes (default: 5242880 = 5MB)
- `ALLOWED_FILE_TYPES`: Comma-separated MIME types (default: image/jpeg, image/png, image/jpg)
- `UPLOAD_PATH`: Upload directory path (default: ./uploads)

### 3. Static File Serving
**File**: `server/app.js`

- Added static file serving for `/uploads` route
- Serves files from `uploads/` directory
- Images are accessible at: `http://localhost:3000/uploads/products/{filename}`

### 4. API Endpoints

#### A. Create Product with Image
**Endpoint**: `POST /api/products`
**Method**: Multipart/form-data
**Auth**: Required (Manager/Admin)
**Fields**:
- Standard product fields (name, sku, product_type, etc.)
- `image`: File field (optional)
- `variants`: JSON string (optional) - if sending as multipart/form-data

**Example**:
```bash
curl -X POST http://localhost:3000/api/products \
  -H "Authorization: Bearer {token}" \
  -F "name=T-Shirt" \
  -F "product_type=FG" \
  -F "image=@/path/to/image.jpg"
```

#### B. Update Product with Image
**Endpoint**: `PUT /api/products/:id`
**Method**: Multipart/form-data
**Auth**: Required (Manager/Admin)
**Fields**:
- Standard product update fields
- `image`: File field (optional) - replaces existing image

**Example**:
```bash
curl -X PUT http://localhost:3000/api/products/1 \
  -H "Authorization: Bearer {token}" \
  -F "name=Updated T-Shirt" \
  -F "image=@/path/to/new-image.jpg"
```

#### C. Upload Product Image (Dedicated Endpoint)
**Endpoint**: `POST /api/products/:id/image`
**Method**: Multipart/form-data
**Auth**: Required (Manager/Admin)
**Fields**:
- `image`: File field (required)

**Example**:
```bash
curl -X POST http://localhost:3000/api/products/1/image \
  -H "Authorization: Bearer {token}" \
  -F "image=@/path/to/image.jpg"
```

**Response**:
```json
{
  "success": true,
  "message": "Product image uploaded successfully",
  "data": {
    "product": { ... },
    "image_url": "/uploads/products/image-1234567890-123456789.jpg",
    "filename": "image-1234567890-123456789.jpg"
  }
}
```

---

## File Storage Structure

```
server/
  uploads/
    products/
      image-1234567890-123456789.jpg
      product-9876543210-987654321.png
      ...
```

---

## Error Handling

### File Size Exceeded
**Status**: 400 Bad Request
**Response**:
```json
{
  "success": false,
  "message": "File size exceeds maximum limit of 5MB"
}
```

### Invalid File Type
**Status**: 400 Bad Request
**Response**:
```json
{
  "success": false,
  "message": "Invalid file type. Allowed types: image/jpeg, image/png, image/jpg, image/gif, image/webp"
}
```

### No File Provided
**Status**: 400 Bad Request (for dedicated upload endpoint)
**Response**:
```json
{
  "success": false,
  "message": "No image file provided"
}
```

---

## Security Considerations

1. **File Type Validation**: Only image files are allowed
2. **File Size Limits**: Prevents DoS attacks via large files
3. **Filename Sanitization**: Removes special characters from filenames
4. **Unique Filenames**: Prevents filename collisions and overwrites
5. **Authorization**: Only managers and admins can upload images
6. **Directory Traversal Protection**: Multer handles this by default

---

## Future Enhancements (Not Implemented)

- Image resizing/thumbnails generation
- Multiple images per product
- Image deletion endpoint
- Cloud storage integration (S3, etc.)
- Image compression/optimization
- Image CDN integration

---

## Testing

To test the image upload functionality:

1. **Start the server**:
   ```bash
   npm run dev
   ```

2. **Login to get token**:
   ```bash
   curl -X POST http://localhost:3000/api/auth/login \
     -H "Content-Type: application/json" \
     -d '{"username":"admin","password":"admin123"}'
   ```

3. **Upload product image**:
   ```bash
   curl -X POST http://localhost:3000/api/products/1/image \
     -H "Authorization: Bearer {token}" \
     -F "image=@/path/to/test-image.jpg"
   ```

4. **Verify image is accessible**:
   ```bash
   curl http://localhost:3000/uploads/products/{filename}
   ```

---

## Notes

- Images are stored locally in the `uploads/products/` directory
- The `image_url` field stores the relative path (e.g., `/uploads/products/filename.jpg`)
- When updating a product image, the old image file is not automatically deleted (manual cleanup may be needed)
- The uploads directory is gitignored (except `.gitkeep` files to preserve structure)

---

## Integration with Existing Features

- Image upload is integrated with product creation and update endpoints
- System logs record image upload actions
- Images are included in product retrieval responses
- No breaking changes to existing API functionality (image is optional)

