%%{init: {'theme': 'base'}}%%
sequenceDiagram
    participant Client
    participant FastAPI
    participant AuthMiddleware
    participant DownloadService
    participant ProgressService
    participant WebSocketService
    participant SeriesApp
    participant Database

    Note over Client,Database: Download Flow

    %% Add to queue
    Client->>FastAPI: POST /api/queue/add
    FastAPI->>AuthMiddleware: Validate JWT
    AuthMiddleware-->>FastAPI: OK
    FastAPI->>DownloadService: add_to_queue()
    DownloadService->>Database: save_item()
    Database-->>DownloadService: item_id
    DownloadService-->>FastAPI: [item_ids]
    FastAPI-->>Client: 201 Created

    %% Start queue
    Client->>FastAPI: POST /api/queue/start
    FastAPI->>AuthMiddleware: Validate JWT
    AuthMiddleware-->>FastAPI: OK
    FastAPI->>DownloadService: start_queue_processing()
    
    loop For each pending item
        DownloadService->>SeriesApp: download_episode()
        
        loop Progress updates
            SeriesApp->>ProgressService: emit("progress_updated")
            ProgressService->>WebSocketService: broadcast_to_room()
            WebSocketService-->>Client: WebSocket message
        end
        
        SeriesApp-->>DownloadService: completed
        DownloadService->>Database: update_status()
    end
    
    DownloadService-->>FastAPI: OK
    FastAPI-->>Client: 200 OK
