openapi: 3.0.3
info:
  title: TranscriMed Medical Records API
  description: |
    Medical Records API for TranscriMed platform - handles medical record generation, 
    CRUD operations, and voice corrections.
    
    This API allows you to:
    - Generate medical records from audio or text
    - Manage medical records (create, read, update, delete)
    - Process voice corrections
    - Handle versioning and document history
    
    ## Authentication
    
    All endpoints require OAuth2 authentication with appropriate scopes.
    Include the access token in the Authorization header:
    
    ```
    Authorization: Bearer your_access_token_here
    ```
    
    ## Processing Modes
    
    - **Sync**: Immediate processing, response includes completed record
    - **Async**: Background processing, returns job ID for status tracking
    
  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/medical-records/generate:
    post:
      summary: Generate Medical Record
      description: |
        Generate a medical record from audio or text input using AI processing.
        
        You can provide either:
        - Audio file (base64 encoded) for transcription + generation
        - Text input for direct generation
        
        The system will transcribe audio (if provided), process the content,
        and generate a structured medical record using the specified template.
      operationId: generateMedicalRecord
      tags:
        - Medical Records
      security:
        - OAuth2: [medical_records:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GenerateMedicalRecordRequest'
            examples:
              audio_generation:
                summary: Generate from audio
                value:
                  audio: "UklGRiQAAABXQVZFZm10IBAAAAABAAEAgD4AAIB..."
                  template_id: "template_123"
                  language: "en"
                  patient_id: "patient_456"
                  mode: "async"
                  metadata:
                    appointment_type: "consultation"
              text_generation:
                summary: Generate from text
                value:
                  text: "Patient presents with chest pain and shortness of breath. Vital signs stable."
                  template_id: "template_123"
                  language: "en"
                  patient_id: "patient_456"
                  mode: "async"
      responses:
        '202':
          description: Medical record generation started
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AsyncJobResponse'
              example:
                success: true
                data:
                  jobId: "job_456"
                  status: "queued"
                  statusUrl: "https://api.transcrimed.com.br/api/v1/pipeline/jobs/job_456"
                  eventsUrl: "https://api.transcrimed.com.br/api/v1/pipeline/jobs/job_456/events"
                  estimatedCompletionAt: "2024-01-15T10:35:00Z"
                meta:
                  request_id: "req_123"
                  timestamp: "2024-01-15T10:30:00Z"
        '400':
          description: Invalid request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              examples:
                missing_input:
                  summary: Missing audio or text
                  value:
                    success: false
                    error:
                      code: "INVALID_REQUEST"
                      message: "Either audio or text input is required"
                invalid_audio:
                  summary: Invalid audio format
                  value:
                    success: false
                    error:
                      code: "INVALID_AUDIO"
                      message: "Audio must be base64 encoded"
        '401':
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '403':
          description: Insufficient permissions
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '429':
          description: Rate limit exceeded
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

  /api/v1/medical-records:
    get:
      summary: List Medical Records
      description: |
        Retrieve a paginated list of medical records for the authenticated user.
        
        Supports filtering by patient, template, and search text.
        Results are sorted by creation date (newest first) by default.
      operationId: listMedicalRecords
      tags:
        - Medical Records
      security:
        - OAuth2: [medical_records: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 records per page
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 20
        - name: patient_id
          in: query
          description: Filter by patient ID
          schema:
            type: string
        - name: template_id
          in: query
          description: Filter by template ID
          schema:
            type: string
        - name: search
          in: query
          description: Search in title and content
          schema:
            type: string
        - name: sort
          in: query
          description: Sort field
          schema:
            type: string
            enum: [created_at, updated_at, title]
            default: created_at
        - name: order
          in: query
          description: Sort order
          schema:
            type: string
            enum: [asc, desc]
            default: desc
      responses:
        '200':
          description: Medical records retrieved successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MedicalRecordListResponse'
              example:
                success: true
                data:
                  medical_records:
                    - id: "record_123"
                      title: "Cardiology Consultation"
                      content: "# Patient Assessment..."
                      patient_id: "patient_456"
                      template_id: "template_123"
                      created_at: "2024-01-15T10:30:00Z"
                      updated_at: "2024-01-15T10:30:00Z"
                  pagination:
                    page: 1
                    limit: 20
                    total: 45
                    hasNext: true
                    hasPrev: false
                meta:
                  request_id: "req_123"
                  timestamp: "2024-01-15T10:30:00Z"
        '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/medical-records/{id}:
    get:
      summary: Get Medical Record
      description: Retrieve a specific medical record by ID
      operationId: getMedicalRecord
      tags:
        - Medical Records
      security:
        - OAuth2: [medical_records:read]
      parameters:
        - name: id
          in: path
          required: true
          description: Medical record ID
          schema:
            type: string
      responses:
        '200':
          description: Medical record retrieved successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MedicalRecordResponse'
        '404':
          description: Medical record 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'

    put:
      summary: Update Medical Record
      description: Update an existing medical record
      operationId: updateMedicalRecord
      tags:
        - Medical Records
      security:
        - OAuth2: [medical_records:write]
      parameters:
        - name: id
          in: path
          required: true
          description: Medical record ID
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateMedicalRecordRequest'
            example:
              title: "Updated Cardiology Consultation"
              content: "# Updated Patient Assessment\n\nChief Complaint: Resolved chest pain..."
              patient_id: "patient_456"
              metadata:
                updated_reason: "Follow-up results added"
      responses:
        '200':
          description: Medical record updated successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MedicalRecordResponse'
        '400':
          description: Invalid request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          description: Medical record 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: Delete Medical Record
      description: Delete a medical record permanently
      operationId: deleteMedicalRecord
      tags:
        - Medical Records
      security:
        - OAuth2: [medical_records:write]
      parameters:
        - name: id
          in: path
          required: true
          description: Medical record ID
          schema:
            type: string
      responses:
        '200':
          description: Medical record deleted successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SuccessResponse'
              example:
                success: true
                data:
                  message: "Medical record deleted successfully"
                  record_id: "record_123"
                meta:
                  request_id: "req_123"
                  timestamp: "2024-01-15T10:30:00Z"
        '404':
          description: Medical record 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/medical-records/{id}/correct:
    post:
      summary: Voice Correction
      description: |
        Apply voice corrections to a medical record using audio input.
        
        This endpoint processes voice corrections and updates the medical record
        with the corrected content while preserving the original version.
      operationId: correctMedicalRecord
      tags:
        - Medical Records
      security:
        - OAuth2: [medical_records:write]
      parameters:
        - name: id
          in: path
          required: true
          description: Medical record ID
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/VoiceCorrectionRequest'
            example:
              audio: "UklGRiQAAABXQVZFZm10IBAAAAABAAEAgD4AAIB..."
              mode: "async"
              language: "en"
              metadata:
                correction_type: "content_update"
      responses:
        '202':
          description: Voice correction started
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AsyncJobResponse'
        '400':
          description: Invalid request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          description: Medical record 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/medical-records/{id}/versions:
    get:
      summary: Get Medical Record Versions
      description: Retrieve version history for a medical record
      operationId: getMedicalRecordVersions
      tags:
        - Medical Records
      security:
        - OAuth2: [medical_records:read]
      parameters:
        - name: id
          in: path
          required: true
          description: Medical record 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 versions per page
          schema:
            type: integer
            minimum: 1
            maximum: 50
            default: 10
      responses:
        '200':
          description: Medical record versions retrieved successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MedicalRecordVersionsResponse'
              example:
                success: true
                data:
                  versions:
                    - id: "version_123"
                      medical_record_id: "record_123"
                      version_number: 2
                      title: "Cardiology Consultation (Updated)"
                      content: "# Updated Patient Assessment..."
                      changes_summary: "Added follow-up results"
                      created_at: "2024-01-15T11:00:00Z"
                      created_by: "user_456"
                    - id: "version_122"
                      medical_record_id: "record_123"
                      version_number: 1
                      title: "Cardiology Consultation"
                      content: "# Patient Assessment..."
                      changes_summary: "Initial version"
                      created_at: "2024-01-15T10:30:00Z"
                      created_by: "user_456"
                  pagination:
                    page: 1
                    limit: 10
                    total: 2
                    hasNext: false
                    hasPrev: false
                meta:
                  request_id: "req_123"
                  timestamp: "2024-01-15T10:30:00Z"
        '404':
          description: Medical record 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/worklists/ingest:
    post:
      summary: Ingest Worklist Items
      description: |
        Ingest worklist items from partner systems into the TranscriMed platform.
        
        This endpoint allows partners to push worklist data for medical record processing.
        Items can be provided as single objects or arrays and must include proper identifiers.
      operationId: ingestWorklistItems
      tags:
        - Worklists
      security:
        - OAuth2: [worklists:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/WorklistIngestRequest'
            example:
              items:
                - patient_id: "P123456"
                  exam_id: "EX789"
                  patient_name: "João Silva"
                  exam_type: "Echocardiogram"
                  scheduled_date: "2024-01-15T14:30:00Z"
                  priority: "routine"
                  metadata:
                    department: "Cardiology"
      responses:
        '200':
          description: Worklist items ingested successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WorklistIngestResponse'
        '400':
          description: Invalid request or validation errors
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

  /api/v1/worklists/sources:
    get:
      summary: List Worklist Sources
      description: Retrieve all worklist sources for the authenticated user
      operationId: listWorklistSources
      tags:
        - Worklists
      security:
        - OAuth2: [worklists:read]
      responses:
        '200':
          description: Worklist sources retrieved successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WorklistSourcesResponse'

  /api/v1/worklists/items:
    get:
      summary: List Worklist Items
      description: |
        Retrieve worklist items with filtering and pagination support.
        
        Supports filtering by source, status, patient, date range and search text.
      operationId: listWorklistItems
      tags:
        - Worklists
      security:
        - OAuth2: [worklists:read]
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            minimum: 1
            default: 1
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 20
        - name: source
          in: query
          description: Filter by worklist source
          schema:
            type: string
        - name: status
          in: query
          description: Filter by item status
          schema:
            type: string
            enum: [pending, in_progress, completed, cancelled]
        - name: from
          in: query
          description: Filter items from this date
          schema:
            type: string
            format: date-time
        - name: to
          in: query
          description: Filter items to this date
          schema:
            type: string
            format: date-time
        - name: search
          in: query
          description: Search in patient name and exam details
          schema:
            type: string
      responses:
        '200':
          description: Worklist items retrieved successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WorklistItemsResponse'

  /api/v1/worklists/items/{id}:
    patch:
      summary: Update Worklist Item Status
      description: Update the status of a specific worklist item
      operationId: updateWorklistItem
      tags:
        - Worklists
      security:
        - OAuth2: [worklists:manage]
      parameters:
        - name: id
          in: path
          required: true
          description: Worklist item ID
          schema:
            type: string
            format: uuid
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateWorklistItemRequest'
            example:
              status: "in_progress"
              reason: "Started processing"
      responses:
        '200':
          description: Worklist item updated successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WorklistItemResponse'

  /api/v1/worklists/items/{id}/link-record:
    post:
      summary: Link Worklist Item to Medical Record
      description: Associate a worklist item with a generated medical record
      operationId: linkWorklistToRecord
      tags:
        - Worklists
      security:
        - OAuth2: [worklists:manage]
      parameters:
        - name: id
          in: path
          required: true
          description: Worklist item ID
          schema:
            type: string
            format: uuid
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/LinkWorklistRequest'
            example:
              record_id: "record_123"
      responses:
        '200':
          description: Worklist item linked successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WorklistItemResponse'

  /api/v1/worklists/items/{id}/deliver:
    post:
      summary: Trigger Worklist Delivery
      description: Schedule delivery of completed worklist item to partner system
      operationId: triggerWorklistDelivery
      tags:
        - Worklists
      security:
        - OAuth2: [worklists:manage]
      parameters:
        - name: id
          in: path
          required: true
          description: Worklist item ID
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Delivery scheduled successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SuccessResponse'

components:
  schemas:
    GenerateMedicalRecordRequest:
      type: object
      properties:
        audio:
          type: string
          format: base64
          description: Base64 encoded audio file (WAV, MP3, M4A, etc.)
        text:
          type: string
          description: Direct text input for generation
        mode:
          type: string
          enum: [async]
          default: async
          deprecated: true
          description: |
            Processing mode. The synchronous (`sync`) mode was removed in
            4.1.0; only `async` is accepted. Field retained for client
            compatibility and will be ignored if omitted.
        template_id:
          type: string
          description: Template to use for generation
        language:
          type: string
          description: Language for processing (ISO code)
        patient_id:
          type: string
          description: Patient identifier
        metadata:
          type: object
          additionalProperties: true
          description: Additional metadata
      oneOf:
        - required: [audio]
        - required: [text]
      example:
        audio: "UklGRiQAAABXQVZFZm10IBAAAAABAAEAgD4AAIB..."
        template_id: "template_123"
        language: "en"
        patient_id: "patient_456"
        mode: "async"

    UpdateMedicalRecordRequest:
      type: object
      properties:
        title:
          type: string
          description: Medical record title
        content:
          type: string
          description: Medical record content (Markdown)
        patient_id:
          type: string
          description: Patient identifier
        template_id:
          type: string
          description: Template identifier
        metadata:
          type: object
          additionalProperties: true
          description: Additional metadata
      example:
        title: "Updated Cardiology Consultation"
        content: "# Updated Patient Assessment\n\nChief Complaint: Resolved chest pain..."
        patient_id: "patient_456"

    VoiceCorrectionRequest:
      type: object
      required:
        - audio
      properties:
        audio:
          type: string
          format: base64
          description: Base64 encoded audio file with corrections
        mode:
          type: string
          enum: [async]
          default: async
          deprecated: true
          description: |
            Processing mode. The synchronous (`sync`) mode was removed in
            4.1.0; only `async` is accepted. Field retained for client
            compatibility and will be ignored if omitted.
        language:
          type: string
          description: Language for processing (ISO code)
        metadata:
          type: object
          additionalProperties: true
          description: Additional metadata
      example:
        audio: "UklGRiQAAABXQVZFZm10IBAAAAABAAEAgD4AAIB..."
        mode: "async"
        language: "en"

    VoiceCorrectionResponse:
      type: object
      deprecated: true
      description: |
        Deprecated. The voice correction endpoint now returns `AsyncJobResponse`
        (HTTP 202) and the corrected document is delivered via the realtime
        broadcast channel or the job status endpoint. This schema is retained
        only for clients still parsing legacy responses and will be removed in
        a future release.
      properties:
        id:
          type: string
          description: Medical record ID
        title:
          type: string
          description: Medical record title
        content:
          type: string
          description: Corrected document content (HTML/Markdown)
        corrected:
          type: boolean
          description: Whether corrections were applied
        correction:
          type: object
          description: Correction processing details
          properties:
            requestId:
              type: string
              description: Unique request ID for tracking
            changePercentage:
              type: number
              format: float
              description: Percentage of document that was changed
            processingTimeMs:
              type: number
              description: Total processing time in milliseconds
            tokensUsed:
              type: number
              description: Number of LLM tokens used
            transcriptionDurationMs:
              type: number
              description: Audio transcription duration in milliseconds
            normalizationDurationMs:
              type: number
              description: Instruction normalization duration in milliseconds
            correctionDurationMs:
              type: number
              description: Document correction duration in milliseconds
      example:
        id: "record_123"
        title: "Cardiology Consultation"
        content: "# Updated Patient Assessment\n\nChief Complaint: Resolved chest pain..."
        corrected: true
        correction:
          requestId: "corr_abc123"
          changePercentage: 5.2
          processingTimeMs: 3500
          tokensUsed: 1200
          transcriptionDurationMs: 1200
          normalizationDurationMs: 800
          correctionDurationMs: 1500

    MedicalRecord:
      type: object
      properties:
        id:
          type: string
          description: Medical record ID
        user_id:
          type: string
          description: User ID who owns the record
        title:
          type: string
          description: Medical record title
        content:
          type: string
          description: Medical record content (Markdown)
        patient_id:
          type: string
          description: Patient identifier
        template_id:
          type: string
          description: Template used for generation
        metadata:
          type: object
          additionalProperties: true
          description: Additional metadata
        created_at:
          type: string
          format: date-time
          description: Creation timestamp
        updated_at:
          type: string
          format: date-time
          description: Last update timestamp
      required:
        - id
        - user_id
        - title
        - content
        - created_at
        - updated_at
      example:
        id: "record_123"
        user_id: "user_456"
        title: "Cardiology Consultation"
        content: "# Patient Assessment\n\nChief Complaint: Chest pain..."
        patient_id: "patient_456"
        template_id: "template_123"
        created_at: "2024-01-15T10:30:00Z"
        updated_at: "2024-01-15T10:30:00Z"

    MedicalRecordVersion:
      type: object
      properties:
        id:
          type: string
          description: Version ID
        medical_record_id:
          type: string
          description: Associated medical record ID
        version_number:
          type: integer
          description: Version number
        title:
          type: string
          description: Version title
        content:
          type: string
          description: Version content (Markdown)
        changes_summary:
          type: string
          description: Summary of changes
        created_at:
          type: string
          format: date-time
          description: Version creation timestamp
        created_by:
          type: string
          description: User who created this version
      required:
        - id
        - medical_record_id
        - version_number
        - title
        - content
        - created_at
        - created_by

    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

    ProcessingInfo:
      type: object
      description: |
        Processing metadata for legacy synchronous responses. Production
        responses are now async (HTTP 202 + AsyncJobResponse) and do not
        include this object.
      properties:
        mode:
          type: string
          enum: [async]
          description: Processing mode used
        duration_ms:
          type: integer
          description: Processing duration in milliseconds
        template_used:
          type: string
          description: Template name used for generation
      required:
        - mode

    MedicalRecordResponse:
      type: object
      properties:
        success:
          type: boolean
          example: true
        data:
          type: object
          properties:
            medical_record:
              $ref: '#/components/schemas/MedicalRecord'
            processing_info:
              $ref: '#/components/schemas/ProcessingInfo'
        meta:
          $ref: '#/components/schemas/ResponseMeta'
      required:
        - success
        - data
        - meta

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

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

    AsyncJobResponse:
      type: object
      properties:
        success:
          type: boolean
          example: true
        data:
          type: object
          properties:
            jobId:
              type: string
              description: Job ID for tracking
            status:
              type: string
              enum: [queued, in_progress, completed, failed]
              description: Initial job status
            statusUrl:
              type: string
              description: URL for polling job status
            eventsUrl:
              type: string
              description: Server-Sent Events URL for streaming job progress
            realtimeChannel:
              type: string
              description: |
                Supabase realtime channel name (e.g. `correction:<requestId>`)
                used for in-browser correction progress broadcasts. Only
                returned for voice/document correction jobs and only useful
                when authenticated as the same Supabase user that submitted
                the job. Non-Supabase API consumers should ignore this field
                and poll `statusUrl` (or subscribe to `eventsUrl`) instead.
            estimatedCompletionAt:
              type: string
              format: date-time
              description: Estimated completion time
            external_reference_id:
              type: string
              description: |
                Echoed back when the request supplied
                `external_reference_id`; useful for correlating with the
                caller's own ID space.
          example:
            jobId: 'job-9f2a3b'
            status: 'queued'
            statusUrl: 'https://api.transcrimed.com/api/v1/pipeline/jobs/job-9f2a3b'
            eventsUrl: 'https://api.transcrimed.com/api/v1/pipeline/jobs/job-9f2a3b/events'
            realtimeChannel: 'correction:5b6e1a4d-9f7c-4d2c-8e5b-9c3a1f2e6b4d'
            estimatedCompletionAt: '2026-04-28T20:05:00Z'
            external_reference_id: 'partner-ref-123'
        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

    WorklistIngestRequest:
      type: object
      properties:
        items:
          oneOf:
            - $ref: '#/components/schemas/WorklistItemRaw'
            - type: array
              items:
                $ref: '#/components/schemas/WorklistItemRaw'
        source:
          type: string
          description: Source system identifier
      required:
        - items

    WorklistItemRaw:
      type: object
      properties:
        patient_id:
          type: string
          description: Patient identifier from source system
        exam_id:
          type: string
          description: Exam identifier from source system
        patient_name:
          type: string
          description: Patient full name
        exam_type:
          type: string
          description: Type of medical examination
        scheduled_date:
          type: string
          format: date-time
          description: Scheduled examination date
        priority:
          type: string
          enum: [routine, urgent, stat]
          description: Examination priority level
        metadata:
          type: object
          additionalProperties: true
          description: Additional examination metadata
      required:
        - patient_id
        - exam_id
        - patient_name
        - exam_type
        - scheduled_date

    UpdateWorklistItemRequest:
      type: object
      properties:
        status:
          type: string
          enum: [pending, in_progress, completed, cancelled]
          description: New status for the worklist item
        reason:
          type: string
          description: Reason for status change
      required:
        - status

    LinkWorklistRequest:
      type: object
      properties:
        record_id:
          type: string
          description: Medical record ID to link
      required:
        - record_id

    WorklistItem:
      type: object
      properties:
        id:
          type: string
          format: uuid
          description: Worklist item ID
        user_id:
          type: string
          description: User who owns the item
        source:
          type: string
          description: Source system identifier
        patient_id:
          type: string
          description: Patient identifier
        exam_id:
          type: string
          description: Exam identifier
        patient_name:
          type: string
          description: Patient full name
        exam_type:
          type: string
          description: Examination type
        scheduled_date:
          type: string
          format: date-time
          description: Scheduled date
        priority:
          type: string
          enum: [routine, urgent, stat]
          description: Priority level
        status:
          type: string
          enum: [pending, in_progress, completed, cancelled]
          description: Current status
        linked_record_id:
          type: string
          nullable: true
          description: Associated medical record ID
        metadata:
          type: object
          additionalProperties: true
          description: Additional metadata
        created_at:
          type: string
          format: date-time
          description: Creation timestamp
        updated_at:
          type: string
          format: date-time
          description: Last update timestamp

    WorklistIngestResponse:
      type: object
      properties:
        success:
          type: boolean
          example: true
        data:
          type: object
          properties:
            processed:
              type: integer
              description: Number of items processed
            created:
              type: integer
              description: Number of new items created
            updated:
              type: integer
              description: Number of existing items updated
            errors:
              type: array
              items:
                type: string
              description: Processing errors if any
        meta:
          $ref: '#/components/schemas/ResponseMeta'

    WorklistSourcesResponse:
      type: object
      properties:
        success:
          type: boolean
          example: true
        data:
          type: array
          items:
            type: object
            properties:
              source:
                type: string
              item_count:
                type: integer
              last_updated:
                type: string
                format: date-time
        meta:
          $ref: '#/components/schemas/ResponseMeta'

    WorklistItemsResponse:
      type: object
      properties:
        success:
          type: boolean
          example: true
        data:
          type: array
          items:
            $ref: '#/components/schemas/WorklistItem'
        meta:
          $ref: '#/components/schemas/ResponseMeta'

    WorklistItemResponse:
      type: object
      properties:
        success:
          type: boolean
          example: true
        data:
          $ref: '#/components/schemas/WorklistItem'
        meta:
          $ref: '#/components/schemas/ResponseMeta'

  securitySchemes:
    OAuth2:
      type: oauth2
      flows:
        authorizationCode:
          authorizationUrl: /api/oauth/authorize
          tokenUrl: /api/oauth/token
          refreshUrl: /api/oauth/token
          scopes:
            medical_records:read: Read medical records
            medical_records:write: Create and update medical records
            medical_records:delete: Delete medical records
            worklists:read: Read worklist items and sources
            worklists:write: Create and ingest worklist items
            worklists:manage: Update worklist status and link to medical records

tags:
  - name: Medical Records
    description: |
      Medical record management and processing operations.
      
      These endpoints handle the core functionality for medical record
      generation, CRUD operations, and voice corrections.
  - name: Worklists
    description: |
      Worklist integration and management operations.
      
      These endpoints handle worklist ingestion from partner systems,
      item status management, and linking worklist items to medical records.

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