openapi: 3.0.3
info:
  title: API Gateway de Firma Electrónica Avanzada (FEA) - FacMed U.Chile
  description: |
    API REST para la integración de sistemas internos de la Facultad de Medicina con el Core FEA de la Universidad de Chile.
    Permite a los sistemas autorizados solicitar firmas, monitorear estados en tiempo real, recibir webhooks automáticos y descargar documentos firmados con validez legal.
  version: 1.0.0
  contact:
    name: Subdirección de Informática - Facultad de Medicina, U. de Chile
    email: soporte.informatica@med.uchile.cl
    url: https://firmadigital.med.uchile.cl
servers:
  - url: https://firmadigital.med.uchile.cl/public/api/v1
    description: Servidor Oficial de Producción - FacMed U.Chile

security:
  - ApiKeyAuth: []

paths:
  /signatures:
    post:
      summary: Crear una nueva solicitud de firma electrónica
      description: |
        Envía uno o más documentos PDF en Base64 junto a la lista de firmantes institucionales.
        La pasarela gestiona la subida al Core FEA, la sesión de firma y la notificación a los firmantes.
      operationId: createSignatureRequest
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateSignatureRequest'
            example:
              external_reference: "ACTA-2026-0842"
              message: "Firma de Acta de Calificaciones Semestre Otoño 2026"
              signer_type: 1
              callback_url: "https://mi-sistema.med.uchile.cl/api/webhook"
              documents:
                - filename: "acta_calificaciones.pdf"
                  content_base64: "JVBERi0xLjQKMSAwIG9iai... (PDF en Base64) ..."
              signers:
                - rut: "9742831-K"
                  email: "rsanhueza@uchile.cl"
                  name: "Ricardo Sanhueza"
      responses:
        '201':
          description: Solicitud de firma creada exitosamente
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateSignatureResponse'
              example:
                success: true
                request_id: 11
                external_reference: "ACTA-2026-0842"
                status: "pending"
                signing_url: "https://firmador-test.uchile.cl/core/30762"
                message: "Signature request successfully created. Signers notified."
        '400':
          description: JSON inválido o cuerpo vacío
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          description: Cabecera X-API-Key ausente o inválida
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '409':
          description: Conflicto de Idempotencia. Ya existe una solicitud de firma registrada con esta external_reference.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ConflictResponse'
        '413':
          description: Archivo demasiado grande. Excede el límite de 20 MB por documento o 50 MB acumulado.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '422':
          description: Error de validación (RUT inválido según Módulo 11, email no válido, URL de callback no permitida o parámetros obligatorios faltantes)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '500':
          description: Error interno del servidor o error en la comunicación con Core FEA
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

  /signatures/{id}:
    get:
      summary: Consultar estado de una solicitud de firma
      description: Retorna el estado actual de la solicitud, el progreso de cada firmante y los enlaces de descarga.
      operationId: getSignatureStatus
      parameters:
        - name: id
          in: path
          required: true
          description: ID interno de la solicitud retornado al crearla
          schema:
            type: integer
            example: 11
      responses:
        '200':
          description: Estado obtenido exitosamente
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SignatureStatusResponse'
              example:
                request_id: 11
                external_reference: "ACTA-2026-0842"
                status: "completed"
                created_at: "2026-10-16 09:59:48"
                signers:
                  - rut: "009742831K"
                    email: "rsanhueza@uchile.cl"
                    status: "signed"
                    signed_at: "2026-10-16 10:03:59"
                documents:
                  - document_id: 9
                    filename: "acta_calificaciones.pdf"
                    verification_code: "mzt6985heydkdadddo8b7mrmpa"
                    status: "signed"
                    download_url: "https://firmadigital.med.uchile.cl/api/v1/signatures/11/download/9"
        '401':
          description: X-API-Key inválida
        '404':
          description: Solicitud no encontrada o no pertenece al sistema cliente

  /signatures/{id}/download/{doc_id}:
    get:
      summary: Descargar documento PDF (original o firmado)
      description: |
        Descarga el archivo PDF binario correspondiente. Si el proceso de firma ya concluyó, 
        el archivo descargado incluye los estampados de rúbricas, firmas y código QR oficial de validación.
      operationId: downloadDocument
      parameters:
        - name: id
          in: path
          required: true
          description: ID de la solicitud
          schema:
            type: integer
            example: 11
        - name: doc_id
          in: path
          required: true
          description: ID del documento dentro de la solicitud
          schema:
            type: integer
            example: 9
      responses:
        '200':
          description: Archivo PDF binario
          content:
            application/pdf:
              schema:
                type: string
                format: binary
        '401':
          description: No autorizado
        '404':
          description: Documento no encontrado
        '410':
          description: Archivo purgado por cumplimiento del periodo de retención legal

components:
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key
      description: Clave secreta asignada a cada sistema cliente en el panel de administración.

  schemas:
    CreateSignatureRequest:
      type: object
      required:
        - external_reference
        - message
        - signer_type
        - documents
        - signers
      properties:
        external_reference:
          type: string
          description: Identificador único provisto por tu sistema (folio, número de expediente, etc.)
          example: "EXP-2026-0842"
        message:
          type: string
          description: Descripción o asunto visible para los firmantes
          example: "Firma de Convenio de Colaboración Asistencial"
        signer_type:
          type: integer
          enum: [1, 2, 3, 5]
          description: |
            Tipo de firma electrónica:
            * `1`: SEGPRES Atendida (ClaveÚnica / OTP en HSM de Gobierno) - Por Defecto
            * `2`: Esigner Atendida (Clave institucional en HSM UChile)
            * `3`: SEGPRES Desatendida (Procesos masivos)
            * `5`: Firma Simple Atendida
          example: 1
        callback_url:
          type: string
          format: uri
          description: URL del webhook en tu servidor que recibirá el aviso al completarse las firmas.
          example: "https://mi-sistema.med.uchile.cl/api/webhook"
        documents:
          type: array
          minItems: 1
          items:
            $ref: '#/components/schemas/DocumentItem'
        signers:
          type: array
          minItems: 1
          items:
            $ref: '#/components/schemas/SignerItem'

    DocumentItem:
      type: object
      required:
        - filename
        - content_base64
      properties:
        filename:
          type: string
          description: Nombre del archivo PDF
          example: "documento_oficial.pdf"
        content_base64:
          type: string
          description: Contenido completo del archivo PDF codificado en Base64
          example: "JVBERi0xLjQKMSAwIG9iai..."

    SignerItem:
      type: object
      required:
        - rut
        - email
      properties:
        rut:
          type: string
          description: RUT del firmante (con o sin puntos/guión)
          example: "9742831-K"
        email:
          type: string
          format: email
          description: Correo electrónico institucional del firmante
          example: "rsanhueza@uchile.cl"
        name:
          type: string
          description: Nombre completo del firmante (opcional)
          example: "Ricardo Sanhueza"
        position:
          type: object
          description: |
            Ubicación y tamaño personalizado de la rúbrica (estampado institucional).
            Si no se especifica, se utiliza el estándar institucional recomendado por U.Chile
            (200x60 pt en esquina inferior derecha, según Manual Core FEA).
          properties:
            preset:
              type: string
              enum: [bottom_right, bottom_center, bottom_left]
              description: Plantilla rápida de ubicación (por defecto bottom_right)
              example: bottom_right
            page:
              type: integer
              description: Número de página donde estampar la rúbrica (por defecto 1)
              example: 1
            lower_left_x:
              type: integer
              description: Coordenada X inferior izquierda (puntos PDF)
              example: 360
            lower_left_y:
              type: integer
              description: Coordenada Y inferior izquierda (puntos PDF)
              example: 80
            upper_right_x:
              type: integer
              description: Coordenada X superior derecha (puntos PDF)
              example: 560
            upper_right_y:
              type: integer
              description: Coordenada Y superior derecha (puntos PDF)
              example: 140
        static_rubric:
          type: boolean
          description: Si es true, el firmante no podrá desplazar la firma en el visor web. Por defecto false.
          example: false

    CreateSignatureResponse:
      type: object
      properties:
        success:
          type: boolean
          example: true
        request_id:
          type: integer
          description: ID único generado por la pasarela para esta transacción
          example: 11
        external_reference:
          type: string
          example: "EXP-2026-0842"
        status:
          type: string
          enum: [pending, completed, error]
          example: "pending"
        signing_url:
          type: string
          format: uri
          description: URL oficial de la Universidad para acceder directamente a firmar
          example: "https://firmador-test.uchile.cl/core/30762"
        message:
          type: string
          example: "Signature request successfully created. Signers notified."

    SignatureStatusResponse:
      type: object
      properties:
        request_id:
          type: integer
          example: 11
        external_reference:
          type: string
          example: "EXP-2026-0842"
        status:
          type: string
          enum: [pending, completed, error, purged]
          example: "completed"
        created_at:
          type: string
          example: "2026-10-16 09:59:48"
        signers:
          type: array
          items:
            type: object
            properties:
              rut:
                type: string
                example: "009742831K"
              email:
                type: string
                example: "rsanhueza@uchile.cl"
              status:
                type: string
                enum: [pending, signed, rejected]
                example: "signed"
              signed_at:
                type: string
                nullable: true
                example: "2026-10-16 10:03:59"
        documents:
          type: array
          items:
            type: object
            properties:
              document_id:
                type: integer
                example: 9
              filename:
                type: string
                example: "acta_calificaciones.pdf"
              verification_code:
                type: string
                nullable: true
                example: "mzt6985heydkdadddo8b7mrmpa"
              status:
                type: string
                enum: [uploaded, signed, error, purged]
                example: "signed"
              download_url:
                type: string
                format: uri
                example: "https://firmadigital.med.uchile.cl/api/v1/signatures/11/download/9"

    OutboundWebhookPayload:
      type: object
      description: |
        Payload enviado por la pasarela al callback_url del sistema cliente al completarse la firma.
        Cada llamada incluye cabeceras de seguridad criptográfica:
        - `X-FEA-Signature`: Firma HMAC-SHA256 con formato `t={timestamp},v1={hash_hex}` calculada sobre `{timestamp}.{payload_json}` usando la API Key como secreto.
        - `X-FEA-Timestamp`: Marca de tiempo Unix para prevenir ataques de replay.
      properties:
        event:
          type: string
          example: "signature.completed"
        request_id:
          type: integer
          example: 11
        external_reference:
          type: string
          example: "EXP-2026-0842"
        status:
          type: string
          example: "completed"
        timestamp:
          type: string
          format: date-time
          example: "2026-10-16T10:04:00-03:00"
        documents:
          type: array
          items:
            type: object
            properties:
              filename:
                type: string
                example: "acta_calificaciones.pdf"
              verification_code:
                type: string
                example: "mzt6985heydkdadddo8b7mrmpa"
              status:
                type: string
                example: "signed"
              download_url:
                type: string
                format: uri
                example: "https://firmadigital.med.uchile.cl/api/v1/signatures/11/download/9"

    ConflictResponse:
      type: object
      properties:
        error:
          type: string
          example: "Ya existe una solicitud de firma registrada con la referencia externa indicada."
        conflict:
          type: boolean
          example: true
        existing_request_id:
          type: integer
          example: 11
        status:
          type: string
          example: "pending"
        created_at:
          type: string
          example: "2026-10-16 09:59:48"

    ErrorResponse:
      type: object
      properties:
        error:
          type: string
          example: "Acceso Denegado: API Key inválida o sistema cliente inactivo."
