openapi: 3.0.3
info:
  title: Chapi API
  version: 0.0.1
  description: |-
    API pública de Chapi para verificación de antecedentes (KYC/KYB) en Chile a partir
    del RUT. Permite crear o consultar Checks, recuperar el último Check del mes
    calendario en curso, y resolver nombre↔RUT.

    Documentación legible en https://chapi.cl/docs/api/.
servers:
  - url: https://app.chapi.cl
    description: Producción
tags:
  - name: Checks
    description: Verificación de antecedentes a partir de un RUT.
  - name: Rutificador
    description: Resolución entre nombre y RUT.
paths:
  /api/check:
    post:
      operationId: Check Create
      description: |-
        Realiza un nuevo Check a un RUT.

        Respuestas:
        - 200: Check creado o existente (ver schema `ACheckSerializer`). Campo `score`
          es un objeto `{value: float, label: "low" | "medium" | "high"}`. Campo `data`
          es un objeto con contadores por tipo de causa y flags agregados.
        - 400: RUT inválido (`{"message": "Invalid RUT"}`).
        - 402: Saldo insuficiente de créditos (`{"message": "Insufficient balance"}`).
        - 404: No se encontró persona o empresa asociada al RUT (`{"message": "No data found"}`).
      tags:
      - Checks
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                rut:
                  type: string
                  description: RUT to check
                  example: 22222222-2
                  pattern: \d{1,2}\.?\d{3}\.?\d{3}-[\dkK]$
                ai_summary:
                  type: boolean
                  description: Whether to generate AI summary
                  example: true
                  default: false
              required:
              - rut
      security:
      - cookieAuth: []
      - tokenAuth: []
      responses:
        '200':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ACheck'
          description: ''
        '400':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Invalid RUT
        '402':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Insufficient balance
        '404':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: No data found
  /api/check/{rut}:
    get:
      operationId: Check Retrieve
      description: |-
        Retorna detalles del Check mas reciente para el RUT especificado dentro del mes calendario actual.

        Respuestas:
        - 200: Check existente (ver schema `CheckSerializer`).
        - 400: RUT inválido.
        - 404: No existe Check para el RUT dentro del mes calendario en curso.
      parameters:
      - in: path
        name: rut
        schema:
          type: string
          pattern: ^\d{1,2}\.?\d{3}\.?\d{3}-[\dkK]$
        required: true
      tags:
      - Checks
      security:
      - cookieAuth: []
      - tokenAuth: []
      responses:
        '200':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Check'
          description: ''
        '400':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Invalid RUT
        '404':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: No check found for the given RUT in the current calendar month
  /api/name-to-rut:
    post:
      operationId: Name to RUT
      description: |-
        Obtiene un listado de RUTs a partir de un nombre (paginado).

        Respuestas:
        - 200: Envoltorio paginado `{count, page, page_size, total_pages, results: [{rut, full_name}, ...]}`.
        - 400: Nombre ausente o con formato inválido (`{"message": "..."}`).
        - 402: Saldo insuficiente (`{"message": "Insufficient balance"}`).
        - 404: Sin coincidencias o página fuera de rango (`{"message": "No data found"}`).
      parameters:
      - in: query
        name: page
        schema:
          type: integer
        description: Page number (default 1)
      - in: query
        name: page_size
        schema:
          type: integer
        description: Results per page (max 25, default 25)
      tags:
      - Rutificador
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                name:
                  type: string
                  description: Full name to search
                  example: Juan Pérez
              required:
              - name
      security:
      - cookieAuth: []
      - tokenAuth: []
      responses:
        '200':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PaginatedRUTResponse'
          description: ''
        '400':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Missing or invalid name
        '402':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Insufficient balance
        '404':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: No data found
  /api/rut-to-name:
    post:
      operationId: RUT to Name
      description: |-
        Obtiene los datos de una persona a partir de un RUT.

        Respuestas:
        - 200: Lista de coincidencias `[{rut, full_name}, ...]`.
        - 400: RUT inválido o ausente (`{"message": "Invalid RUT"}`).
        - 402: Saldo insuficiente (`{"message": "Insufficient balance"}`).
        - 404: No se encontraron coincidencias (`{"message": "No data found"}`).
      tags:
      - Rutificador
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                rut:
                  type: string
                  description: RUT to look up
                  example: 12345678-5
              required:
              - rut
      security:
      - cookieAuth: []
      - tokenAuth: []
      responses:
        '200':
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/RUT'
          description: ''
        '400':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Invalid or missing RUT
        '402':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Insufficient balance
        '404':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: No data found
components:
  schemas:
    ACheck:
      type: object
      description: Base serializer class.
      properties:
        id:
          type: string
          format: uuid
          readOnly: true
        permalink:
          type: string
          format: uri
          readOnly: true
        rut:
          type: string
          maxLength: 10
        name:
          type: string
        data:
          allOf:
          - $ref: '#/components/schemas/CheckData'
          readOnly: true
        created_at:
          type: string
          format: date-time
          readOnly: true
          title: Creado
        score:
          allOf:
          - $ref: '#/components/schemas/CheckScore'
          readOnly: true
        pdf_report_url:
          type: string
          format: uri
          readOnly: true
        ai_summary:
          type: string
      required:
      - created_at
      - data
      - id
      - name
      - pdf_report_url
      - permalink
      - score
    Check:
      type: object
      description: Base serializer class.
      properties:
        id:
          type: string
          format: uuid
          readOnly: true
        permalink:
          type: string
          format: uri
          readOnly: true
        rut:
          type: string
          maxLength: 10
        name:
          type: string
        data:
          allOf:
          - $ref: '#/components/schemas/CheckData'
          readOnly: true
        created_at:
          type: string
          format: date-time
          readOnly: true
          title: Creado
        score:
          allOf:
          - $ref: '#/components/schemas/CheckScore'
          readOnly: true
        pdf_report_url:
          type: string
          format: uri
          readOnly: true
        ai_summary:
          type: string
      required:
      - created_at
      - data
      - id
      - name
      - pdf_report_url
      - permalink
      - score
    CheckData:
      type: object
      properties:
        causas_penales_count:
          type: integer
        causas_penales_rut_match_count:
          type: integer
        causas_penales_name_match_count:
          type: integer
        causas_civiles_count:
          type: integer
        causas_laborales_count:
          type: integer
        causas_sindicales_count:
          type: integer
        international_sanctions_count:
          type: integer
        pep:
          type: boolean
    CheckScore:
      type: object
      properties:
        value:
          type: number
          format: double
        label:
          $ref: '#/components/schemas/LabelEnum'
      required:
      - label
      - value
    Error:
      type: object
      properties:
        message:
          type: string
      required:
      - message
    LabelEnum:
      enum:
      - low
      - medium
      - high
      type: string
      description: |-
        * `low` - low
        * `medium` - medium
        * `high` - high
    PaginatedRUTResponse:
      type: object
      properties:
        count:
          type: integer
        page:
          type: integer
        page_size:
          type: integer
        total_pages:
          type: integer
        results:
          type: array
          items:
            $ref: '#/components/schemas/RUT'
      required:
      - count
      - page
      - page_size
      - results
      - total_pages
    RUT:
      type: object
      properties:
        rut:
          type: string
          readOnly: true
        full_name:
          type: string
          nullable: true
          maxLength: 255
      required:
      - rut
  securitySchemes:
    cookieAuth:
      type: apiKey
      in: cookie
      name: sessionid
    tokenAuth:
      type: apiKey
      in: header
      name: Authorization
      description: Token-based authentication with required prefix "Token"
