{
  "openapi": "3.1.0",
  "info": {
    "title": "Prescri API",
    "version": "1.0.0",
    "description": "API REST de assinatura digital ICP-Brasil de documentos médicos (Bird ID e VIDaaS). Documentação completa: https://www.prescri.com.br/documentacao-api",
    "contact": {
      "name": "Prescri",
      "url": "https://www.prescri.com.br/documentacao-api"
    }
  },
  "servers": [
    {
      "url": "https://suykokupoevtdfalrzue.supabase.co/functions/v1",
      "description": "Produção"
    }
  ],
  "security": [
    {
      "ApiKey": [],
      "ApiSecret": []
    }
  ],
  "components": {
    "securitySchemes": {
      "ApiKey": {
        "type": "apiKey",
        "in": "header",
        "name": "X-API-Key"
      },
      "ApiSecret": {
        "type": "apiKey",
        "in": "header",
        "name": "X-API-Secret"
      }
    },
    "schemas": {
      "Error": {
        "type": "object",
        "properties": {
          "error": {
            "type": "string"
          },
          "status": {
            "type": "string"
          }
        }
      },
      "Patient": {
        "type": "object",
        "required": [
          "full_name",
          "cpf"
        ],
        "properties": {
          "full_name": {
            "type": "string"
          },
          "cpf": {
            "type": "string",
            "description": "11 dígitos"
          },
          "phone": {
            "type": "string",
            "example": "5511999998888"
          }
        }
      },
      "SignatureCreateRequest": {
        "type": "object",
        "required": [
          "provider",
          "doctor_cpf"
        ],
        "properties": {
          "provider": {
            "type": "string",
            "enum": [
              "birdid",
              "vidaas"
            ]
          },
          "doctor_cpf": {
            "type": "string",
            "description": "11 dígitos"
          },
          "doctor_full_name": {
            "type": "string"
          },
          "doctor_crm": {
            "type": "string"
          },
          "doctor_crm_uf": {
            "type": "string"
          },
          "doctor_specialty": {
            "type": "string"
          },
          "doctor_email": {
            "type": "string",
            "format": "email"
          },
          "doctor_phone": {
            "type": "string"
          },
          "pdf_base64": {
            "type": "string",
            "description": "Use pdf_base64 OU pdf_url, nunca ambos"
          },
          "pdf_url": {
            "type": "string",
            "format": "uri"
          },
          "document_type": {
            "type": "string",
            "example": "Receituário Médico"
          },
          "prescription_type_id": {
            "type": "string",
            "format": "uuid"
          },
          "external_id": {
            "type": "string"
          },
          "external_metadata": {
            "type": "object",
            "additionalProperties": true
          },
          "webhook_url": {
            "type": "string",
            "format": "uri"
          },
          "redirect_url": {
            "type": "string",
            "format": "uri"
          },
          "session_id": {
            "type": "string",
            "format": "uuid"
          },
          "patient": {
            "$ref": "#/components/schemas/Patient"
          },
          "stamp_options": {
            "type": "object",
            "properties": {
              "position": {
                "type": "string",
                "enum": [
                  "top-left",
                  "top-right",
                  "bottom-left",
                  "bottom-right"
                ]
              },
              "marginX": {
                "type": "number"
              },
              "marginY": {
                "type": "number"
              },
              "qrSize": {
                "type": "number"
              }
            }
          },
          "sncr_reservation_token": {
            "type": "string",
            "description": "Token de pré-reserva obtido em POST /api-sncr-reserve (opcional). Usa o número já reservado em vez de consumir um novo.",
            "example": "rsv_0a1b2c…"
          },
          "sncr_stamp": {
            "type": "object",
            "description": "Opcional. Quando presente, a Prescri desenha o quadro \"NUMERAÇÃO SNCR\" no PDF enviado, antes da assinatura. Sem este objeto o PDF segue inalterado (comportamento legado).",
            "properties": {
              "position": {
                "type": "string",
                "enum": [
                  "top-left",
                  "top-right",
                  "top-center",
                  "bottom-left",
                  "bottom-right",
                  "bottom-center",
                  "custom"
                ],
                "default": "top-right"
              },
              "x": {
                "type": "number",
                "description": "Somente com position=custom. Pontos a partir da borda esquerda."
              },
              "y": {
                "type": "number",
                "description": "Somente com position=custom. Pontos a partir do topo."
              },
              "marginX": {
                "type": "number",
                "default": 24
              },
              "marginY": {
                "type": "number",
                "default": 24
              },
              "page": {
                "description": "first (padrão), last, all ou o número da página.",
                "oneOf": [
                  {
                    "type": "string",
                    "enum": [
                      "first",
                      "last",
                      "all"
                    ]
                  },
                  {
                    "type": "integer",
                    "minimum": 1
                  }
                ]
              },
              "width": {
                "type": "number",
                "minimum": 120,
                "maximum": 400,
                "default": 180
              },
              "uf": {
                "type": "string",
                "description": "UF impressa no quadro. Padrão: doctor_crm_uf."
              }
            }
          },
          "document": {
            "type": "object",
            "description": "Opcional. Gera o PDF no modelo Prescri (logo, paciente, texto e/ou itens) em vez de enviar pdf_base64/pdf_url. Exige title e body ou items.",
            "properties": {
              "title": {
                "type": "string"
              },
              "body": {
                "type": "string"
              },
              "items": {
                "type": "array",
                "items": {
                  "type": "object",
                  "properties": {
                    "name": {
                      "type": "string"
                    },
                    "quantity": {
                      "type": "string"
                    },
                    "dosage": {
                      "type": "string"
                    }
                  },
                  "required": [
                    "name"
                  ]
                }
              },
              "observations": {
                "type": "string"
              },
              "cid10": {
                "type": "string"
              },
              "city": {
                "type": "string"
              },
              "uf": {
                "type": "string"
              },
              "branding": {
                "type": "object",
                "properties": {
                  "logo_url": {
                    "type": "string"
                  },
                  "logo_base64": {
                    "type": "string"
                  },
                  "logo_position": {
                    "type": "string",
                    "enum": [
                      "left",
                      "right"
                    ]
                  },
                  "clinic_name": {
                    "type": "string"
                  },
                  "clinic_cnes": {
                    "type": "string",
                    "description": "CNES do estabelecimento (rodapé). Se omitido, usa o CNES cadastrado na empresa."
                  },
                  "clinic_cnpj": {
                    "type": "string",
                    "description": "CNPJ (só dígitos ou formatado; rodapé). Se omitido, usa o CNPJ cadastrado na empresa. Médico autônomo pode omitir."
                  },
                  "clinic_phone": {
                    "type": "string",
                    "description": "Telefone de contato (rodapé)."
                  },
                  "clinic_address": {
                    "type": "string"
                  }
                }
              },
              "patient": {
                "type": "object",
                "properties": {
                  "name": {
                    "type": "string"
                  },
                  "cpf": {
                    "type": "string"
                  },
                  "birth_date": {
                    "type": "string"
                  },
                  "gender": {
                    "type": "string"
                  },
                  "address": {
                    "type": "string"
                  }
                }
              }
            },
            "required": [
              "title"
            ]
          }
        }
      },
      "Signature": {
        "type": "object",
        "properties": {
          "signature_id": {
            "type": "string",
            "format": "uuid"
          },
          "status": {
            "type": "string",
            "enum": [
              "pending_authorization",
              "authorized",
              "signed",
              "failed",
              "cancelled"
            ]
          },
          "provider": {
            "type": "string"
          },
          "sign_url": {
            "type": "string"
          },
          "pdf_url": {
            "type": "string"
          },
          "signature_token": {
            "type": "string"
          },
          "signed_at": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "expires_at": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "external_id": {
            "type": [
              "string",
              "null"
            ]
          },
          "metadata": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": true
          },
          "error": {
            "type": [
              "string",
              "null"
            ]
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          },
          "sncr_number": {
            "type": [
              "string",
              "null"
            ],
            "description": "Numeração SNCR (Anvisa) usada no documento controlado"
          },
          "sncr_type": {
            "type": [
              "string",
              "null"
            ],
            "example": "NRB"
          },
          "sncr_stamped": {
            "type": "boolean",
            "description": "true quando o quadro de numeração SNCR foi estampado no PDF pela Prescri."
          }
        }
      },
      "Session": {
        "type": "object",
        "properties": {
          "session_id": {
            "type": "string",
            "format": "uuid"
          },
          "status": {
            "type": "string",
            "enum": [
              "pending_authorization",
              "active",
              "expired",
              "revoked"
            ]
          },
          "provider": {
            "type": "string"
          },
          "doctor_cpf": {
            "type": "string"
          },
          "doctor_id": {
            "type": "string"
          },
          "authorize_url": {
            "type": "string"
          },
          "authorized_at": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "expires_at": {
            "type": "string",
            "format": "date-time"
          },
          "signatures_count": {
            "type": "integer"
          },
          "last_used_at": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "session_lifetime_seconds": {
            "type": "integer"
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "SncrReservation": {
        "type": "object",
        "properties": {
          "sncr_number": {
            "type": "string",
            "example": "2602.6-53.0000001"
          },
          "sncr_type": {
            "type": "string",
            "example": "NRB"
          },
          "reservation_token": {
            "type": "string",
            "example": "rsv_0a1b2c…"
          },
          "expires_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      }
    }
  },
  "paths": {
    "/api-signatures-create": {
      "post": {
        "summary": "Criar assinatura",
        "description": "Envia o PDF (base64 ou URL) e inicia a assinatura. Com session_id ativo, o documento volta já assinado.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SignatureCreateRequest"
              },
              "example": {
                "provider": "birdid",
                "doctor_cpf": "12345678901",
                "doctor_full_name": "Dra. Ana Souza",
                "doctor_crm": "123456",
                "doctor_crm_uf": "SP",
                "pdf_url": "https://seusistema.com/receita.pdf",
                "document_type": "Receituário Médico",
                "webhook_url": "https://seusistema.com/webhooks/prescri",
                "patient": {
                  "full_name": "João da Silva",
                  "cpf": "98765432100",
                  "phone": "5511999998888"
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Assinatura criada",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Signature"
                }
              }
            }
          },
          "400": {
            "description": "Requisição inválida",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Credenciais inválidas",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api-signatures-get": {
      "get": {
        "summary": "Consultar assinatura",
        "parameters": [
          {
            "name": "id",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Status da assinatura",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Signature"
                }
              }
            }
          },
          "404": {
            "description": "Não encontrada",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api-signatures-pdf": {
      "get": {
        "summary": "Baixar PDF assinado",
        "parameters": [
          {
            "name": "id",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "PDF assinado",
            "content": {
              "application/pdf": {
                "schema": {
                  "type": "string",
                  "format": "binary"
                }
              }
            }
          },
          "409": {
            "description": "Documento ainda não assinado",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api-signatures-cancel": {
      "post": {
        "summary": "Cancelar assinatura",
        "parameters": [
          {
            "name": "id",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Cancelada",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "ok": {
                      "type": "boolean"
                    },
                    "status": {
                      "type": "string"
                    }
                  }
                }
              }
            }
          },
          "409": {
            "description": "Já assinado",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api-signatures-sessions-create": {
      "post": {
        "summary": "Criar sessão de assinatura",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "provider",
                  "doctor_cpf"
                ],
                "properties": {
                  "provider": {
                    "type": "string",
                    "enum": [
                      "birdid",
                      "vidaas"
                    ]
                  },
                  "doctor_cpf": {
                    "type": "string"
                  },
                  "session_lifetime_seconds": {
                    "type": "integer",
                    "default": 43200,
                    "description": "Máx. 604800 (7 dias) no Bird ID e 43200 (12h) no VIDaaS"
                  },
                  "redirect_url": {
                    "type": "string",
                    "format": "uri"
                  }
                }
              },
              "example": {
                "provider": "birdid",
                "doctor_cpf": "12345678901",
                "session_lifetime_seconds": 604800,
                "redirect_url": "https://seusistema.com/sessao-autorizada"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Sessão criada",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Session"
                }
              }
            }
          }
        }
      }
    },
    "/api-signatures-sessions-get": {
      "get": {
        "summary": "Consultar sessão",
        "parameters": [
          {
            "name": "session_id",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Status da sessão",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Session"
                }
              }
            }
          }
        }
      }
    },
    "/api-document-types": {
      "get": {
        "summary": "Listar tipos de documento",
        "responses": {
          "200": {
            "description": "Tipos aceitos em document_type / prescription_type_id",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "document_types": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "prescription_type_id": {
                            "type": "string",
                            "format": "uuid"
                          },
                          "name": {
                            "type": "string"
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/api-sncr-balance": {
      "get": {
        "summary": "Saldo de numeração SNCR do médico",
        "parameters": [
          {
            "name": "doctor_cpf",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Saldo por tipo (sncr_type, available, required, can_issue)"
          }
        }
      }
    },
    "/api-sncr-reserve": {
      "post": {
        "summary": "Pré-reservar numeração SNCR",
        "description": "Reserva o próximo número da carteira do médico para que o parceiro imprima a numeração no PDF antes de enviá-lo para assinatura. A reserva expira em 30 minutos por padrão (5 a 120 via ttl_minutes) e o número volta para a carteira se não for usada.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "doctor_cpf",
                  "sncr_type"
                ],
                "properties": {
                  "doctor_cpf": {
                    "type": "string",
                    "description": "11 dígitos"
                  },
                  "sncr_type": {
                    "type": "string",
                    "enum": [
                      "NRA",
                      "NRB",
                      "NRB2",
                      "NRR",
                      "NRT",
                      "RCE",
                      "RET"
                    ]
                  },
                  "ttl_minutes": {
                    "type": "integer",
                    "minimum": 5,
                    "maximum": 120,
                    "default": 30
                  }
                }
              },
              "example": {
                "doctor_cpf": "12345678901",
                "sncr_type": "NRB",
                "ttl_minutes": 30
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Número reservado",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SncrReservation"
                }
              }
            }
          },
          "400": {
            "description": "Requisição inválida",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Credenciais inválidas",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "description": "Carteira do médico sem numeração (sncr_no_numbers)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "delete": {
        "summary": "Liberar pré-reserva",
        "description": "Devolve o número reservado para a carteira do médico.",
        "parameters": [
          {
            "name": "reservation_token",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Reserva liberada"
          },
          "401": {
            "description": "Credenciais inválidas"
          },
          "404": {
            "description": "Reserva não encontrada ou já utilizada"
          }
        }
      }
    }
  }
}