openapi: 3.1.0
info:
  title: TranscriMed Jobs API
  description: |
    Jobs API for TranscriMed platform - handles asynchronous job tracking, 
    status monitoring, and result retrieval.
    
    This API allows you to:
    - Track status of async medical record processing jobs
    - Monitor job progress and completion
    - Retrieve job results and logs
    - Cancel running jobs
    
    ## Job Lifecycle
    
    Jobs go through the following states:
    1. **queued** - Job is waiting to be processed
    2. **in_progress** - Job is currently being processed
    3. **completed** - Job finished successfully
    4. **failed** - Job failed with errors
    5. **cancelled** - Job was cancelled by user
    
    ## Authentication
    
    All endpoints require OAuth2 authentication with appropriate scopes.
    Include the access token in the Authorization header:
    
    ```
    Authorization: Bearer your_access_token_here
    ```
    
  version: 1.0.0
  contact:
    name: TranscriMed API Support
    url: https://developers.transcrimed.com.br/support
    email: developers@transcrimed.com.br
  license:
    name: MIT
    url: https://opensource.org/licenses/MIT

servers:
  - url: https://api.transcrimed.com.br
    description: Production server (use test credentials for test mode)
  - url: http://localhost:54321/functions/v1/api-gateway
    description: Local development server

paths:
  /api/v1/jobs:
    get:
      summary: List Jobs
      description: |
        Retrieve a paginated list of jobs for the authenticated user.
        
        Supports filtering by status, type, and sorting by various fields.
        Results are sorted by creation date (newest first) by default.
      operationId: listJobs
      tags:
        - Jobs
      security:
        - OAuth2: [jobs:read]
      parameters:
        - name: page
          in: query
          description: Page number (1-based)
          schema:
            type: integer
            minimum: 1
            default: 1
        - name: limit
          in: query
          description: Number of jobs per page
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 20
        - name: status
          in: query
          description: Filter by job status
          schema:
            type: string
            enum: [queued, in_progress, completed, failed, cancelled]
        - name: type
          in: query
          description: Filter by job type
          schema:
            type: string
            enum: [medical_record_generation, document_correction, template_processing, voice_correction]
        - name: sort
          in: query
          description: Sort field
          schema:
            type: string
            enum: [created_at, updated_at, priority, status]
            default: created_at
        - name: order
          in: query
          description: Sort order
          schema:
            type: string
            enum: [asc, desc]
            default: desc
      responses:
        '200':
          description: Jobs retrieved successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/JobListResponse'
              example:
                success: true
                data:
                  jobs:
                    - id: "job_123"
                      type: "medical_record_generation"
                      status: "completed"
                      progress: 100
                      created_at: "2024-01-15T10:30:00Z"
                      updated_at: "2024-01-15T10:33:00Z"
                      completed_at: "2024-01-15T10:33:00Z"
                      medical_record_id: "record_456"
                      priority: 1
                      retry_count: 0
                      max_retries: 3
                      timeout_seconds: 300
                    - id: "job_124"
                      type: "voice_correction"
                      status: "in_progress"
                      progress: 45
                      created_at: "2024-01-15T10:35:00Z"
                      updated_at: "2024-01-15T10:37:00Z"
                      started_at: "2024-01-15T10:36:00Z"
                      estimated_completion_at: "2024-01-15T10:40:00Z"
                      medical_record_id: "record_789"
                      priority: 1
                      retry_count: 0
                      max_retries: 3
                      timeout_seconds: 300
                  pagination:
                    page: 1
                    limit: 20
                    total: 45
                    hasNext: true
                    hasPrev: false
                meta:
                  request_id: "req_123"
                  timestamp: "2024-01-15T10:30:00Z"
        '400':
          description: Invalid query parameters
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '403':
          description: Insufficient permissions
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

  /api/v1/jobs/{id}:
    get:
      summary: Get Job Details
      description: Retrieve detailed information about a specific job
      operationId: getJob
      tags:
        - Jobs
      security:
        - OAuth2: [jobs:read]
      parameters:
        - name: id
          in: path
          required: true
          description: Job ID
          schema:
            type: string
      responses:
        '200':
          description: Job details retrieved successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/JobResponse'
              example:
                success: true
                data:
                  job:
                    id: "job_123"
                    user_id: "user_456"
                    client_id: "client_789"
                    type: "medical_record_generation"
                    status: "completed"
                    input_data:
                      audio: "UklGRiQAAABXQVZFZm10IBAAAAABAAEAgD4AAIB..."
                      template_id: "template_123"
                      language: "en"
                    result_data:
                      medical_record_id: "record_456"
                      processing_duration_ms: 3500
                    progress: 100
                    created_at: "2024-01-15T10:30:00Z"
                    updated_at: "2024-01-15T10:33:00Z"
                    started_at: "2024-01-15T10:30:30Z"
                    completed_at: "2024-01-15T10:33:00Z"
                    medical_record_id: "record_456"
                    priority: 1
                    retry_count: 0
                    max_retries: 3
                    timeout_seconds: 300
                meta:
                  request_id: "req_123"
                  timestamp: "2024-01-15T10:30:00Z"
        '404':
          description: Job not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '403':
          description: Insufficient permissions
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

    delete:
      summary: Cancel Job
      description: |
        Cancel a running job. Only jobs in 'queued' or 'in_progress' status can be cancelled.
        
        Cancelled jobs cannot be restarted and will remain in 'cancelled' status.
      operationId: cancelJob
      tags:
        - Jobs
      security:
        - OAuth2: [jobs:write]
      parameters:
        - name: id
          in: path
          required: true
          description: Job ID
          schema:
            type: string
      responses:
        '200':
          description: Job cancelled successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SuccessResponse'
              example:
                success: true
                data:
                  message: "Job cancelled successfully"
                  job_id: "job_123"
                meta:
                  request_id: "req_123"
                  timestamp: "2024-01-15T10:30:00Z"
        '400':
          description: Job cannot be cancelled (already completed/failed)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                success: false
                error:
                  code: "INVALID_JOB_STATUS"
                  message: "Job cannot be cancelled in current status: completed"
        '404':
          description: Job not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '403':
          description: Insufficient permissions
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

  /api/v1/jobs/{id}/logs:
    get:
      summary: Get Job Logs
      description: |
        Retrieve execution logs for a specific job.
        
        Logs provide detailed information about job execution steps,
        including debug information, warnings, and errors.
      operationId: getJobLogs
      tags:
        - Jobs
      security:
        - OAuth2: [jobs:read]
      parameters:
        - name: id
          in: path
          required: true
          description: Job ID
          schema:
            type: string
        - name: page
          in: query
          description: Page number (1-based)
          schema:
            type: integer
            minimum: 1
            default: 1
        - name: limit
          in: query
          description: Number of log entries per page
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 50
        - name: level
          in: query
          description: Filter by log level
          schema:
            type: string
            enum: [debug, info, warn, error]
      responses:
        '200':
          description: Job logs retrieved successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/JobLogsResponse'
              example:
                success: true
                data:
                  logs:
                    - id: "log_123"
                      job_id: "job_123"
                      level: "info"
                      message: "Job started processing"
                      timestamp: "2024-01-15T10:30:30Z"
                      metadata:
                        step: "initialization"
                    - id: "log_124"
                      job_id: "job_123"
                      level: "info"
                      message: "Audio transcription completed"
                      timestamp: "2024-01-15T10:31:15Z"
                      metadata:
                        step: "transcription"
                        duration_ms: 45000
                    - id: "log_125"
                      job_id: "job_123"
                      level: "info"
                      message: "Medical record generated successfully"
                      timestamp: "2024-01-15T10:33:00Z"
                      metadata:
                        step: "generation"
                        record_id: "record_456"
                  pagination:
                    page: 1
                    limit: 50
                    total: 8
                    hasNext: false
                    hasPrev: false
                meta:
                  request_id: "req_123"
                  timestamp: "2024-01-15T10:30:00Z"
        '404':
          description: Job not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '403':
          description: Insufficient permissions
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

  /api/v1/jobs/{id}/result:
    get:
      summary: Get Job Result
      description: |
        Retrieve the result data from a completed job.
        
        Only available for jobs in 'completed' status. 
        The result structure varies by job type.
      operationId: getJobResult
      tags:
        - Jobs
      security:
        - OAuth2: [jobs:read]
      parameters:
        - name: id
          in: path
          required: true
          description: Job ID
          schema:
            type: string
      responses:
        '200':
          description: Job result retrieved successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/JobResultResponse'
              examples:
                medical_record_generation:
                  summary: Medical record generation result
                  value:
                    success: true
                    data:
                      result:
                        medical_record_id: "record_456"
                        processing_duration_ms: 3500
                        template_used: "Cardiology Template"
                        transcription_confidence: 0.95
                      medical_record_id: "record_456"
                    meta:
                      request_id: "req_123"
                      timestamp: "2024-01-15T10:30:00Z"
                voice_correction:
                  summary: Voice correction result
                  value:
                    success: true
                    data:
                      result:
                        corrections_applied: 3
                        processing_duration_ms: 2100
                        confidence_score: 0.92
                      medical_record_id: "record_789"
                    meta:
                      request_id: "req_123"
                      timestamp: "2024-01-15T10:30:00Z"
        '400':
          description: Job not completed
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                success: false
                error:
                  code: "JOB_NOT_COMPLETED"
                  message: "Job is not completed. Current status: in_progress"
        '404':
          description: Job not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '403':
          description: Insufficient permissions
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

components:
  schemas:
    Job:
      type: object
      properties:
        id:
          type: string
          description: Unique job identifier
        user_id:
          type: string
          description: User ID who owns the job
        client_id:
          type: string
          description: OAuth2 client ID (for partner integrations)
        type:
          type: string
          enum: [medical_record_generation, document_correction, template_processing, voice_correction]
          description: Type of job
        status:
          type: string
          enum: [queued, in_progress, completed, failed, cancelled]
          description: Current job status
        input_data:
          type: object
          additionalProperties: true
          description: Job input parameters
        result_data:
          type: object
          additionalProperties: true
          description: Job result data (only for completed jobs)
        error_data:
          type: object
          additionalProperties: true
          description: Error details (only for failed jobs)
        progress:
          type: integer
          minimum: 0
          maximum: 100
          description: Job progress percentage
        estimated_completion_at:
          type: string
          format: date-time
          description: Estimated completion time
        started_at:
          type: string
          format: date-time
          description: Job start time
        completed_at:
          type: string
          format: date-time
          description: Job completion time
        created_at:
          type: string
          format: date-time
          description: Job creation timestamp
        updated_at:
          type: string
          format: date-time
          description: Last update timestamp
        priority:
          type: integer
          minimum: 1
          maximum: 10
          description: Job priority (1 = highest, 10 = lowest)
        retry_count:
          type: integer
          minimum: 0
          description: Number of retry attempts
        max_retries:
          type: integer
          minimum: 0
          description: Maximum number of retries allowed
        timeout_seconds:
          type: integer
          minimum: 1
          description: Job timeout in seconds
        medical_record_id:
          type: string
          description: Associated medical record ID
        template_id:
          type: string
          description: Associated template ID
      required:
        - id
        - user_id
        - type
        - status
        - progress
        - created_at
        - updated_at
        - priority
        - retry_count
        - max_retries
        - timeout_seconds
      example:
        id: "job_123"
        user_id: "user_456"
        client_id: "client_789"
        type: "medical_record_generation"
        status: "completed"
        progress: 100
        created_at: "2024-01-15T10:30:00Z"
        updated_at: "2024-01-15T10:33:00Z"
        completed_at: "2024-01-15T10:33:00Z"
        priority: 1
        retry_count: 0
        max_retries: 3
        timeout_seconds: 300

    JobLog:
      type: object
      properties:
        id:
          type: string
          description: Log entry ID
        job_id:
          type: string
          description: Associated job ID
        level:
          type: string
          enum: [debug, info, warn, error]
          description: Log level
        message:
          type: string
          description: Log message
        timestamp:
          type: string
          format: date-time
          description: Log timestamp
        metadata:
          type: object
          additionalProperties: true
          description: Additional log metadata
      required:
        - id
        - job_id
        - level
        - message
        - timestamp
      example:
        id: "log_123"
        job_id: "job_123"
        level: "info"
        message: "Job started processing"
        timestamp: "2024-01-15T10:30:30Z"
        metadata:
          step: "initialization"

    PaginationInfo:
      type: object
      properties:
        page:
          type: integer
          description: Current page number
        limit:
          type: integer
          description: Records per page
        total:
          type: integer
          description: Total number of records
        hasNext:
          type: boolean
          description: Whether there are more pages
        hasPrev:
          type: boolean
          description: Whether there are previous pages
      required:
        - page
        - limit
        - total
        - hasNext
        - hasPrev

    JobResponse:
      type: object
      properties:
        success:
          type: boolean
          example: true
        data:
          type: object
          properties:
            job:
              $ref: '#/components/schemas/Job'
        meta:
          $ref: '#/components/schemas/ResponseMeta'
      required:
        - success
        - data
        - meta

    JobListResponse:
      type: object
      properties:
        success:
          type: boolean
          example: true
        data:
          type: object
          properties:
            jobs:
              type: array
              items:
                $ref: '#/components/schemas/Job'
            pagination:
              $ref: '#/components/schemas/PaginationInfo'
        meta:
          $ref: '#/components/schemas/ResponseMeta'
      required:
        - success
        - data
        - meta

    JobLogsResponse:
      type: object
      properties:
        success:
          type: boolean
          example: true
        data:
          type: object
          properties:
            logs:
              type: array
              items:
                $ref: '#/components/schemas/JobLog'
            pagination:
              $ref: '#/components/schemas/PaginationInfo'
        meta:
          $ref: '#/components/schemas/ResponseMeta'
      required:
        - success
        - data
        - meta

    JobResultResponse:
      type: object
      properties:
        success:
          type: boolean
          example: true
        data:
          type: object
          properties:
            result:
              type: object
              additionalProperties: true
              description: Job-specific result data
            medical_record_id:
              type: string
              description: Associated medical record ID
        meta:
          $ref: '#/components/schemas/ResponseMeta'
      required:
        - success
        - data
        - meta

    SuccessResponse:
      type: object
      properties:
        success:
          type: boolean
          example: true
        data:
          type: object
          additionalProperties: true
        meta:
          $ref: '#/components/schemas/ResponseMeta'
      required:
        - success
        - data
        - meta

    ErrorResponse:
      type: object
      properties:
        success:
          type: boolean
          example: false
        error:
          type: object
          properties:
            code:
              type: string
              description: Error code
            message:
              type: string
              description: Error message
            details:
              type: object
              additionalProperties: true
              description: Additional error details
        meta:
          $ref: '#/components/schemas/ResponseMeta'
      required:
        - success
        - error
        - meta

    ResponseMeta:
      type: object
      properties:
        request_id:
          type: string
          description: Unique request identifier
        timestamp:
          type: string
          format: date-time
          description: Response timestamp
      required:
        - request_id
        - timestamp

  securitySchemes:
    OAuth2:
      type: oauth2
      flows:
        authorizationCode:
          authorizationUrl: /api/oauth/authorize
          tokenUrl: /api/oauth/token
          refreshUrl: /api/oauth/token
          scopes:
            jobs:read: Read job status and results
            jobs:write: Create, cancel and manage jobs

tags:
  - name: Jobs
    description: |
      Asynchronous job management operations.
      
      These endpoints handle tracking and management of background jobs
      created by async medical record processing operations.

externalDocs:
  description: TranscriMed Developer Portal
  url: https://developers.transcrimed.com.br