# Media API

Upload and manage files — property photos, lease documents, ID cards, energy certificates. Files are stored securely in S3 with tenant isolation and optional encryption for sensitive documents.

## Quick Example

```bash
# Upload a property photo
curl -X POST https://api.faireplace.com/api/media/upload/ESTATE/<estate_uuid> \
  -H "Authorization: Bearer $API_KEY" \
  -F "file=@appartement-sejour.jpg"

# Download a file
curl https://api.faireplace.com/api/media/download/<media_uuid> \
  -H "Authorization: Bearer $API_KEY" \
  -o downloaded-file.pdf
```

## Common Workflows

### Upload property photos
1. `POST /api/v1/media/upload/ESTATE/{id}` — Upload photos for an apartment
2. `PUT /api/v1/media/{entity_type}/{entity_id}/{media_id}/role` — Set `PRIMARY_PHOTO` for the main image
3. `GET /api/v1/media/ESTATE/{id}` — List all media for the unit

### Store lease documents securely
1. `POST /api/v1/media/upload/LEASE/{id}` — Upload with automatic CRITICAL security level for lease PDFs
2. `PUT /api/v1/media/{id}/role` — Assign `LEASE_ORIGINAL` or `LEASE_SIGNED` role
3. Documents are encrypted with SSE-C at rest

---

## Overview

The Media API provides comprehensive file management including:
- **Document Storage**: Lease agreements, contracts, certificates
- **Image Management**: Property photos, floor plans, inspection images
- **File Security**: Access control and permissions with SSE-C encryption
- **Entity Associations**: Link media to properties, leases, contacts
- **File Validation**: MIME type and size restrictions
- **Role Management**: Assign specific roles to media (AVATAR, ID_DOCUMENT, PRIMARY_PHOTO, etc.)
- **Tag System**: Organize media with searchable tags

## Authentication

Requires **PropertiesRead**, **PropertiesWrite**, or **PropertiesDelete** permissions.

## Base URL

All media endpoints: `/api/v1/media`

---

## Core Operations

### Upload Media
**POST** `/api/v1/media/upload/{entity_type}/{entity_id}`

Upload a file and attach it immediately to the target entity.

**Path Parameters:**
- `entity_type`: Type of entity (PLACE, ESTATE, ROOM, EQUIPMENT, LEASE, OWNER, CONTACT, LESSEE)
- `entity_id`: UUID of the target entity

**Request (multipart/form-data):**
```
file: [binary file data]
```

**Response:**
```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "url": "https://s3.bucket.com/tenant123/media/file.pdf",
  "media_type": "application/pdf",
  "file_size": 1048576,
  "security_level": "CRITICAL",
  "encryption_key_id": "key-123",
  "checksum": "sha256-hash",
  "tags": ["lease", "contract"],
  "roles": ["LEASE_ORIGINAL"],
  "created_at": "2024-01-15T10:30:00Z",
  "updated_at": "2024-01-15T10:30:00Z"
}
```

### List Media by Entity
**GET** `/api/v1/media/{entity_type}/{entity_id}`

Get all media attached to a specific entity.

**Path Parameters:**
- `entity_type`: Type of entity
- `entity_id`: UUID of the entity

**Response:**
```json
[
  {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "url": "https://s3.bucket.com/tenant123/media/file.pdf",
    "media_type": "application/pdf",
    "file_size": 1048576,
    "security_level": "CRITICAL",
    "encryption_key_id": "key-123",
    "checksum": "sha256-hash",
    "tags": ["lease", "contract"],
    "roles": ["LEASE_ORIGINAL"],
    "created_at": "2024-01-15T10:30:00Z",
    "updated_at": "2024-01-15T10:30:00Z"
  }
]
```

### Search Media by Tags
**GET** `/api/v1/media/search`

Search media using tags with optional entity filtering.

**Query Parameters:**
- `tags`: Comma-separated list of tags (lowercase)
- `match_all`: If true (default), all tags must match; else any tag
- `entity_type`: Optional entity type filter
- `entity_id`: Optional entity ID filter

### Update Media Tags
**PUT** `/api/v1/media/{id}/tags`

Replace all tags for a media item.

**Request:**
```json
{
  "tags": ["updated", "tags", "list"]
}
```

### Assign Role to Media
**PUT** `/api/v1/media/{entity_type}/{entity_id}/{media_id}/role`

Assign a unique role to a media for an entity.

**Path Parameters:**
- `entity_type`: Type of entity
- `entity_id`: UUID of the entity
- `media_id`: UUID of the media

**Request:**
```json
{
  "role": "primary_photo"
}
```

### Clear Role Assignment
**DELETE** `/api/v1/media/{entity_type}/{entity_id}/role/{role}`

Remove role assignment for an entity.

### Get Media by Role
**GET** `/api/v1/media/{entity_type}/{entity_id}/role/{role}`

Get the media with a specific role for an entity.

### Serve Media
**GET** `/api/v1/media/serve/{id}`

Serve media content. Returns JSON for unencrypted media, binary for encrypted media.

### Download Media
**GET** `/api/v1/media/download/{id}`

Force download of media as binary stream with Content-Disposition header.

### Delete Media
**DELETE** `/api/v1/media/{id}`

Delete media (removes both S3 object and database record).

---

## Entity Types

Media can be associated with:
- `PLACE` - Building or complex media
- `ESTATE` - Unit-specific media  
- `ROOM` - Room photos and documentation
- `EQUIPMENT` - Equipment manuals and photos
- `LEASE` - Lease-related documents
- `OWNER` - Owner documentation
- `CONTACT` - Contact documentation
- `LESSEE` - Lessee documentation

---

## Media Roles

Media can be assigned specific roles for different entities:
- `AVATAR` - Profile picture or avatar
- `ID_DOCUMENT` - Identity document
- `PRIMARY_PHOTO` - Main photo for the entity
- `LEASE_ORIGINAL` - Original lease document
- `LEASE_SIGNED` - Signed lease document

---

## Security Levels

### STANDARD
- **Allowed Types**: Images (JPEG, PNG, GIF), PDFs, Documents
- **Max Size**: 10MB
- **Access**: Normal authenticated access
- **Encryption**: No encryption

### SENSITIVE
- **Allowed Types**: PDFs, Documents only
- **Max Size**: 5MB
- **Access**: Restricted access with additional permissions
- **Encryption**: Optional SSE-C encryption

### CRITICAL
- **Allowed Types**: PDFs, Documents only
- **Max Size**: 5MB
- **Access**: Highly restricted access
- **Encryption**: Mandatory SSE-C encryption

---

## File Type Support

**Images:**
- `image/jpeg`, `image/png`, `image/gif`, `image/webp`

**Documents:**
- `application/pdf`
- `application/msword`
- `application/vnd.openxmlformats-officedocument.wordprocessingml.document`

**Archives:**
- `application/zip`

---

## Error Responses

**400 Bad Request**
```json
{
  "error": "ValidationError",
  "message": "File type not allowed",
  "details": {
    "allowed_types": ["image/jpeg", "image/png", "application/pdf"]
  }
}
```

**413 Payload Too Large**
```json
{
  "error": "FileSizeError",
  "message": "File size exceeds maximum allowed",
  "max_size": 10485760
}
```

---

## Worker Endpoints

### Serve Media for Workers
**GET** `/api/v1/media/worker/{id}`

Endpoint for workers (requires specific API key/Bearer token).
Returns file as Base64 JSON.

**Headers:**
- `X-Tenant-ID`: Tenant identifier
- `X-Worker-Type`: Worker type (e.g., signature-processor, otp-validator)

### Upload Signed PDF
**POST** `/api/v1/media/upload-signed/{media_id}`

Upload a signed PDF from a worker. Document is stored in secure mode (SSE-C) with checksum.

**Headers:**
- `X-Tenant-ID`: Tenant identifier
- `X-Worker-Type`: Worker type

**Request:** PDF binary data

---

## Common Use Cases

### Property Marketing
1. Upload property photos with `entity_type=ESTATE`
2. Assign `PRIMARY_PHOTO` role to main property image
3. Add floor plans and layouts with appropriate tags

### Document Management
1. Upload lease agreements with `security_level=CRITICAL`
2. Assign `LEASE_ORIGINAL` role to original documents
3. Store signed documents with `LEASE_SIGNED` role

### Equipment Documentation
1. Upload equipment manuals with `entity_type=EQUIPMENT`
2. Store warranty documents with appropriate tags
3. Photo documentation for maintenance

### Contact Management
1. Upload ID documents with `entity_type=CONTACT`
2. Assign `ID_DOCUMENT` role to identity documents
3. Add profile photos with `AVATAR` role

---

## Integration Notes

- **File Storage**: Secure S3 storage with tenant isolation
- **Encryption**: SSE-C encryption for sensitive documents
- **Checksum Verification**: SHA-256 integrity checking
- **Role Management**: Unique role assignment per entity
- **Tag System**: Searchable tags for media organization
- **Multi-tenancy**: Complete tenant isolation and access control
- **Worker Support**: Specialized endpoints for automated processes