{
  "openapi": "3.1.0",
  "info": {
    "title": "Pearfy API",
    "version": "1.0.0",
    "description": "API pública v1 da Pearfy (gateway de infoproduto). Autenticação por API key do produtor (pk_live_...). Valores monetários sempre em CENTAVOS (BRL)."
  },
  "servers": [
    {
      "url": "https://app.pearfy.com/api/v1"
    }
  ],
  "security": [
    {
      "apiKeyBearer": []
    },
    {
      "apiKeyHeader": []
    }
  ],
  "tags": [
    {
      "name": "Autenticação",
      "description": "OAuth2 client_credentials (drop-in)."
    },
    {
      "name": "Conta",
      "description": "Dados da conta do produtor."
    },
    {
      "name": "Produtos",
      "description": "Produtos do produtor."
    },
    {
      "name": "Ofertas",
      "description": "Ofertas (preços/planos) de um produto."
    },
    {
      "name": "Vendas",
      "description": "Vendas e reembolsos."
    },
    {
      "name": "Estatísticas",
      "description": "Agregados de vendas por período."
    }
  ],
  "paths": {
    "/oauth/token": {
      "post": {
        "tags": [
          "Autenticação"
        ],
        "summary": "Troca a API key por um access_token",
        "description": "Fluxo OAuth2 client_credentials. Envie a API key como client_secret (ou client_id) e receba de volta a própria chave como access_token Bearer. grant_type é ignorado. Aceita JSON ou x-www-form-urlencoded. Público (sem header de auth). Rate limit: 60 req/min por IP.",
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/TokenRequest"
              },
              "example": {
                "grant_type": "client_credentials",
                "client_id": "pk_live_xxx",
                "client_secret": "pk_live_xxx"
              }
            },
            "application/x-www-form-urlencoded": {
              "schema": {
                "$ref": "#/components/schemas/TokenRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Credencial válida; token devolvido.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TokenResponse"
                },
                "example": {
                  "access_token": "pk_live_xxx",
                  "token_type": "Bearer",
                  "expires_in": 86400,
                  "scope": "products sales stats"
                }
              }
            }
          },
          "400": {
            "description": "client_secret/client_id ausentes.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OAuthError"
                },
                "example": {
                  "error": "invalid_request"
                }
              }
            }
          },
          "401": {
            "description": "Chave inexistente, revogada ou expirada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OAuthError"
                },
                "example": {
                  "error": "invalid_client"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    },
    "/account-details": {
      "get": {
        "tags": [
          "Conta"
        ],
        "summary": "Dados da conta do produtor",
        "description": "Retorna os dados da conta do produtor dono da chave e os escopos concedidos à chave. Responde a qualquer chave válida, mas os campos document e phone só são incluídos quando a chave tem o escopo 'account' — sem ele, eles são omitidos da resposta.",
        "responses": {
          "200": {
            "description": "Dados da conta.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AccountDetails"
                },
                "example": {
                  "id": "a1b2c3d4-0000-0000-0000-000000000000",
                  "legal_name": "Fulano Silva",
                  "document": "12345678900",
                  "phone": "+5515999999999",
                  "created_at": "2026-01-15T12:34:56.000Z",
                  "scopes": [
                    "sales",
                    "stats"
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    },
    "/products": {
      "get": {
        "tags": [
          "Produtos"
        ],
        "summary": "Lista produtos",
        "description": "Lista os produtos do produtor autenticado (paginado, mais recentes primeiro).",
        "x-required-scope": "products",
        "parameters": [
          {
            "$ref": "#/components/parameters/PageSize"
          },
          {
            "$ref": "#/components/parameters/PageNumber"
          }
        ],
        "responses": {
          "200": {
            "description": "Lista paginada de produtos.",
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/ListEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "array",
                          "items": {
                            "$ref": "#/components/schemas/Product"
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "object": "list",
                  "pagination": {
                    "page_size": 20,
                    "page_number": 1,
                    "count": 3
                  },
                  "data": [
                    {
                      "id": "uuid",
                      "name": "Curso X",
                      "slug": "curso-x-a1b2c3",
                      "status": "publicado",
                      "type": "curso",
                      "description": "...",
                      "created_at": "2026-07-01T12:00:00Z",
                      "updated_at": "2026-07-02T09:00:00Z"
                    }
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "tags": [
          "Produtos"
        ],
        "summary": "Cria um produto",
        "description": "Cria um produto sempre em status 'rascunho' e automaticamente a oferta padrão com o preço informado (em centavos). Publicar exige PATCH status=publicado com os gates.",
        "x-required-scope": "products",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ProductCreate"
              },
              "example": {
                "name": "Meu Curso",
                "price": 19700,
                "type": "curso"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Produto criado (rascunho).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Product"
                },
                "example": {
                  "id": "uuid",
                  "name": "Meu Curso",
                  "slug": "meu-curso-a1b2c3",
                  "status": "rascunho",
                  "type": "curso",
                  "description": null,
                  "created_at": "2026-07-12T00:00:00Z",
                  "updated_at": "2026-07-12T00:00:00Z"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "422": {
            "$ref": "#/components/responses/InvalidRequest"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/products/{id}": {
      "parameters": [
        {
          "$ref": "#/components/parameters/ProductId"
        }
      ],
      "get": {
        "tags": [
          "Produtos"
        ],
        "summary": "Detalhe de um produto",
        "x-required-scope": "products",
        "responses": {
          "200": {
            "description": "Produto.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Product"
                },
                "example": {
                  "id": "uuid",
                  "name": "Curso X",
                  "slug": "curso-x-a1b2c3",
                  "status": "publicado",
                  "type": "curso",
                  "description": "...",
                  "created_at": "2026-07-01T12:00:00Z",
                  "updated_at": "2026-07-02T09:00:00Z"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      },
      "patch": {
        "tags": [
          "Produtos"
        ],
        "summary": "Edita um produto",
        "description": "Edita campos do produto e/ou muda status. Publicar (status=publicado) aplica os gates de completude e KYC: se faltar campo → 422 not_publishable; se o produtor não for verificado → 422 kyc_required.",
        "x-required-scope": "products",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ProductUpdate"
              },
              "example": {
                "delivery_types": [
                  "external"
                ],
                "delivery_url": "https://area.exemplo.com",
                "status": "publicado"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Produto atualizado. Quando a edicao mexe na ENTREGA de um produto ja publicado e o estado final fica incompleto, o produto e REBAIXADO pra rascunho e a resposta traz `unpublished` explicando o que faltou.",
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/Product"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "unpublished": {
                          "type": "object",
                          "description": "So aparece quando o produto foi rebaixado pra rascunho por esta edicao.",
                          "properties": {
                            "reason": {
                              "type": "string",
                              "enum": [
                                "incomplete_delivery"
                              ]
                            },
                            "missing": {
                              "type": "array",
                              "items": {
                                "type": "string"
                              },
                              "description": "O que falta pra publicar de novo."
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "examples": {
                  "atualizado": {
                    "summary": "Edicao normal",
                    "value": {
                      "id": "1f2e…",
                      "name": "Curso de Trafego",
                      "slug": "curso-de-trafego",
                      "status": "publicado",
                      "type": "curso",
                      "description": "…",
                      "delivery": [
                        "pearfy_members",
                        "email_access"
                      ],
                      "created_at": "2026-08-01T12:00:00Z",
                      "updated_at": "2026-08-20T09:30:00Z"
                    }
                  },
                  "rebaixado": {
                    "summary": "Rebaixado por entrega incompleta",
                    "value": {
                      "id": "1f2e…",
                      "name": "Curso de Trafego",
                      "slug": "curso-de-trafego",
                      "status": "rascunho",
                      "type": "curso",
                      "description": "…",
                      "delivery": [
                        "pearfy_members"
                      ],
                      "created_at": "2026-08-01T12:00:00Z",
                      "updated_at": "2026-08-20T09:30:00Z",
                      "unpublished": {
                        "reason": "incomplete_delivery",
                        "missing": [
                          "uma aula publicada na area de membros"
                        ]
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "422": {
            "description": "Validação (invalid_request), sem campos (no_fields), não publicável (not_publishable) ou KYC exigido (kyc_required).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_request": {
                    "value": {
                      "error": "invalid_request",
                      "detail": "name: mínimo 2 caracteres"
                    }
                  },
                  "no_fields": {
                    "value": {
                      "error": "no_fields"
                    }
                  },
                  "not_publishable": {
                    "value": {
                      "error": "not_publishable",
                      "detail": "Complete antes de publicar: uma aula publicada na area de membros."
                    }
                  },
                  "kyc_required": {
                    "value": {
                      "error": "kyc_required",
                      "detail": "Verificação de identidade necessária"
                    }
                  }
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "delete": {
        "tags": [
          "Produtos"
        ],
        "summary": "Exclui um produto (soft-delete)",
        "description": "Soft-delete: seta deleted_at e status='arquivado'. Reversível. Deletar de novo retorna 404.",
        "x-required-scope": "products",
        "responses": {
          "200": {
            "description": "Produto excluído.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DeletedResponse"
                },
                "example": {
                  "id": "uuid",
                  "deleted": true
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/products/{id}/offers": {
      "parameters": [
        {
          "$ref": "#/components/parameters/ProductId"
        }
      ],
      "get": {
        "tags": [
          "Ofertas"
        ],
        "summary": "Lista ofertas de um produto",
        "description": "Retorna TODAS as ofertas do produto (não paginado). Ordena a padrão primeiro, depois por data de criação. Envelope sem pagination.",
        "x-required-scope": "products",
        "responses": {
          "200": {
            "description": "Lista de ofertas (sem paginação).",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "object": {
                      "type": "string",
                      "const": "list"
                    },
                    "data": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/Offer"
                      }
                    }
                  }
                },
                "example": {
                  "object": "list",
                  "data": [
                    {
                      "id": "uuid",
                      "product_id": "uuid",
                      "name": null,
                      "code": "ABC123",
                      "checkout_url": "https://pay.pearfy.com/ABC123",
                      "price": 19700,
                      "currency": "BRL",
                      "payment_methods": [
                        "pix",
                        "credit_card",
                        "boleto"
                      ],
                      "installments_max": 12,
                      "is_default": true,
                      "active": true,
                      "recurrence": null,
                      "recurrence_limit": null,
                      "created_at": "2026-07-01T12:00:00Z"
                    }
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      },
      "post": {
        "tags": [
          "Ofertas"
        ],
        "summary": "Cria uma oferta",
        "description": "Cria uma oferta (preço/plano) no produto. Máximo 10 ofertas ativas por produto. Ofertas criadas via API não recebem 'code', portanto checkout_url vem null.",
        "x-required-scope": "products",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/OfferCreate"
              },
              "example": {
                "name": "Plano Anual",
                "price": 49700,
                "recurrence_period": "annual",
                "payment_methods": [
                  "pix",
                  "card"
                ]
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Oferta criada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Offer"
                },
                "example": {
                  "id": "uuid",
                  "product_id": "uuid",
                  "name": "Plano Anual",
                  "code": null,
                  "checkout_url": null,
                  "price": 49700,
                  "currency": "BRL",
                  "payment_methods": [
                    "pix",
                    "credit_card"
                  ],
                  "installments_max": 12,
                  "is_default": false,
                  "active": true,
                  "recurrence": "annual",
                  "recurrence_limit": null,
                  "created_at": "2026-07-12T00:00:00Z"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "422": {
            "description": "Validação (invalid_request) ou limite de ofertas atingido (offer_limit).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_request": {
                    "value": {
                      "error": "invalid_request",
                      "detail": "price: obrigatório"
                    }
                  },
                  "offer_limit": {
                    "value": {
                      "error": "offer_limit",
                      "detail": "Máximo de 10 ofertas por produto"
                    }
                  }
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/products/{id}/offers/{offerId}": {
      "parameters": [
        {
          "$ref": "#/components/parameters/ProductId"
        },
        {
          "$ref": "#/components/parameters/OfferId"
        }
      ],
      "patch": {
        "tags": [
          "Ofertas"
        ],
        "summary": "Edita uma oferta",
        "description": "Edita uma oferta do produto. recurrence_period NÃO é editável aqui. is_default=false é ignorado (só transferir a padrão marcando outra como true).",
        "x-required-scope": "products",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/OfferUpdate"
              },
              "example": {
                "price": 24700,
                "is_default": true
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Oferta atualizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Offer"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "422": {
            "description": "Validação (invalid_request) ou nenhum campo aplicável (no_fields).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_request": {
                    "value": {
                      "error": "invalid_request",
                      "detail": "price: inteiro positivo"
                    }
                  },
                  "no_fields": {
                    "value": {
                      "error": "no_fields"
                    }
                  }
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "delete": {
        "tags": [
          "Ofertas"
        ],
        "summary": "Remove uma oferta",
        "description": "Remove a oferta. Bloqueia remover a última oferta ativa (422 last_offer) e a oferta padrão (422 default_offer). Oferta que já teve pedido é desativada em vez de apagada: a resposta traz deleted:false e deactivated:true.",
        "x-required-scope": "products",
        "responses": {
          "200": {
            "description": "Oferta removida.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DeletedResponse"
                },
                "example": {
                  "id": "oid",
                  "deleted": true
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "422": {
            "description": "Não é possível remover a única oferta ativa do produto.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "last_offer",
                  "detail": "Não dá pra remover a única oferta ativa do produto."
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/sales": {
      "get": {
        "tags": [
          "Vendas"
        ],
        "summary": "Lista vendas",
        "description": "Lista as vendas (pedidos) do produtor, ordenadas por created_at desc, com paginação e filtros. Pedidos de teste não entram. Valor de status/payment_method inválido é ignorado silenciosamente.",
        "x-required-scope": "sales",
        "parameters": [
          {
            "name": "status",
            "in": "query",
            "required": false,
            "description": "Filtro por status.",
            "schema": {
              "type": "string",
              "enum": [
                "paid",
                "waiting_payment",
                "refused",
                "refunded",
                "chargedback"
              ]
            }
          },
          {
            "name": "payment_method",
            "in": "query",
            "required": false,
            "description": "Filtro por método de pagamento.",
            "schema": {
              "type": "string",
              "enum": [
                "pix",
                "credit_card",
                "boleto"
              ]
            }
          },
          {
            "name": "product_id",
            "in": "query",
            "required": false,
            "description": "Filtra por produto: ID curto (K7M3Q9) ou uuid.",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "start_date",
            "in": "query",
            "required": false,
            "description": "created_at >= start_date (ISO 8601).",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "end_date",
            "in": "query",
            "required": false,
            "description": "created_at <= end_date (ISO 8601).",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "$ref": "#/components/parameters/PageSize"
          },
          {
            "$ref": "#/components/parameters/PageNumber"
          }
        ],
        "responses": {
          "200": {
            "description": "Lista paginada de vendas.",
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/ListEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "array",
                          "items": {
                            "$ref": "#/components/schemas/Sale"
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "object": "list",
                  "pagination": {
                    "page_size": 20,
                    "page_number": 1,
                    "count": 137
                  },
                  "data": [
                    {
                      "id": "a1b2",
                      "reference": "or_pagarme_123",
                      "status": "paid",
                      "payment_method": "pix",
                      "created_at": "2026-07-10T12:00:00Z",
                      "updated_at": "2026-07-10T12:03:00Z",
                      "approved_date": "2026-07-10T12:03:00Z",
                      "refunded_at": null,
                      "currency": "BRL",
                      "charge_amount": 9700,
                      "net_amount": 8588,
                      "product": {
                        "id": "prod-uuid"
                      },
                      "customer": {
                        "name": "Fulano",
                        "email": "f@x.com",
                        "cpf": "000",
                        "mobile": "5511"
                      }
                    }
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/sales/{id}": {
      "parameters": [
        {
          "$ref": "#/components/parameters/SaleId"
        }
      ],
      "get": {
        "tags": [
          "Vendas"
        ],
        "summary": "Detalhe de uma venda",
        "description": "Detalhe de uma venda do produtor. Igual ao item da lista, porém com product.name resolvido.",
        "x-required-scope": "sales",
        "responses": {
          "200": {
            "description": "Venda.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Sale"
                },
                "example": {
                  "id": "a1b2",
                  "reference": "or_pagarme_123",
                  "status": "paid",
                  "payment_method": "credit_card",
                  "created_at": "2026-07-10T12:00:00Z",
                  "updated_at": "2026-07-10T12:03:00Z",
                  "approved_date": "2026-07-10T12:03:00Z",
                  "refunded_at": null,
                  "currency": "BRL",
                  "charge_amount": 9700,
                  "net_amount": 8588,
                  "product": {
                    "id": "prod-uuid",
                    "name": "Meu Curso"
                  },
                  "customer": {
                    "name": "Fulano",
                    "email": "f@x.com",
                    "cpf": "000",
                    "mobile": "5511"
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    },
    "/sales/{id}/refund": {
      "parameters": [
        {
          "$ref": "#/components/parameters/SaleId"
        }
      ],
      "post": {
        "tags": [
          "Vendas"
        ],
        "summary": "Reembolsa uma venda",
        "description": "Solicita o reembolso de uma venda aprovada. Estorna de verdade no PSP antes de marcar no banco. Síncrono. Idempotente: reembolsar de novo → 422 not_refundable.",
        "x-required-scope": "sales_refund",
        "responses": {
          "200": {
            "description": "Reembolso efetuado.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RefundResponse"
                },
                "example": {
                  "id": "a1b2",
                  "status": "refunded"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "422": {
            "description": "Venda não é reembolsável (não aprovada ou já reembolsada).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not_refundable",
                  "message": "Só vendas aprovadas podem ser reembolsadas"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "502": {
            "description": "Falha no estorno junto ao provedor de pagamento.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "gateway_error",
                  "message": "Falha ao estornar"
                }
              }
            }
          }
        }
      }
    },
    "/stats": {
      "get": {
        "tags": [
          "Estatísticas"
        ],
        "summary": "Estatísticas de vendas por período",
        "description": "Agregados de vendas do produtor num período. gross_amount e net_amount vêm em CENTAVOS e somam SÓ vendas em BRL; by_currency traz os totais de cada moeda presente (BRL incluso), em centavos da própria moeda. Pedidos de teste não entram. Default do período: últimos 30 dias.",
        "x-required-scope": "stats",
        "parameters": [
          {
            "name": "start_date",
            "in": "query",
            "required": false,
            "description": "Início do período (ISO 8601). Default: agora − 30 dias.",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "end_date",
            "in": "query",
            "required": false,
            "description": "Fim do período (ISO 8601). Default: agora.",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Estatísticas do período.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Stats"
                },
                "example": {
                  "period": {
                    "start_date": "2026-06-01T00:00:00Z",
                    "end_date": "2026-06-30T23:59:59Z"
                  },
                  "orders_count": 42,
                  "sales_count": 30,
                  "refunded_count": 3,
                  "gross_amount": 1500000,
                  "net_amount": 1275000,
                  "currency": "BRL",
                  "by_currency": {
                    "BRL": {
                      "orders_count": 40,
                      "sales_count": 28,
                      "refunded_count": 3,
                      "gross_amount": 1500000,
                      "net_amount": 1275000
                    },
                    "USD": {
                      "orders_count": 2,
                      "sales_count": 2,
                      "refunded_count": 0,
                      "gross_amount": 19400,
                      "net_amount": 17000
                    }
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "apiKeyBearer": {
        "type": "http",
        "scheme": "bearer",
        "description": "API key do produtor no header Authorization: Bearer pk_live_..."
      },
      "apiKeyHeader": {
        "type": "apiKey",
        "in": "header",
        "name": "x-api-key",
        "description": "API key do produtor no header x-api-key: pk_live_..."
      }
    },
    "parameters": {
      "PageSize": {
        "name": "page_size",
        "in": "query",
        "required": false,
        "description": "Itens por página. Default 50, min 1, max 100.",
        "schema": {
          "type": "integer",
          "minimum": 1,
          "maximum": 100,
          "default": 50
        }
      },
      "PageNumber": {
        "name": "page_number",
        "in": "query",
        "required": false,
        "description": "Página (1-based). Default 1, min 1.",
        "schema": {
          "type": "integer",
          "minimum": 1,
          "default": 1
        }
      },
      "ProductId": {
        "name": "id",
        "in": "path",
        "required": true,
        "description": "ID curto do produto (K7M3Q9) ou uuid.",
        "schema": {
          "type": "string"
        }
      },
      "OfferId": {
        "name": "offerId",
        "in": "path",
        "required": true,
        "description": "ID da oferta (deve pertencer ao produto e ao produtor).",
        "schema": {
          "type": "string",
          "format": "uuid"
        }
      },
      "SaleId": {
        "name": "id",
        "in": "path",
        "required": true,
        "description": "ID da venda (orders.id).",
        "schema": {
          "type": "string",
          "format": "uuid"
        }
      }
    },
    "responses": {
      "Unauthorized": {
        "description": "Chave ausente (missing_api_key) ou inválida/revogada/expirada (invalid_api_key).",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "examples": {
              "missing_api_key": {
                "value": {
                  "error": "missing_api_key"
                }
              },
              "invalid_api_key": {
                "value": {
                  "error": "invalid_api_key"
                }
              }
            }
          }
        }
      },
      "Forbidden": {
        "description": "Escopo insuficiente para a chave.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "example": {
              "error": "insufficient_scope",
              "required": "products"
            }
          }
        }
      },
      "NotFound": {
        "description": "Recurso não encontrado ou não pertence ao produtor.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "example": {
              "error": "not_found"
            }
          }
        }
      },
      "InvalidRequest": {
        "description": "Corpo inválido (validação).",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "example": {
              "error": "invalid_request",
              "detail": "name: mínimo 2 caracteres"
            }
          }
        }
      },
      "InternalError": {
        "description": "Erro interno.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "example": {
              "error": "internal_error"
            }
          }
        }
      },
      "RateLimited": {
        "description": "Muitas requisições. 300 req/min por IP em /api/v1; 60 req/min por IP em /oauth/token.",
        "headers": {
          "Retry-After": {
            "description": "Segundos até a próxima janela.",
            "schema": {
              "type": "integer"
            }
          },
          "X-RateLimit-Limit": {
            "description": "Limite da janela.",
            "schema": {
              "type": "integer"
            }
          },
          "X-RateLimit-Remaining": {
            "description": "Requisições restantes (0 no 429).",
            "schema": {
              "type": "integer"
            }
          },
          "X-RateLimit-Reset": {
            "description": "Reset da janela (ISO 8601).",
            "schema": {
              "type": "string"
            }
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "type": "object",
              "properties": {
                "error": {
                  "type": "string"
                }
              }
            },
            "example": {
              "error": "Muitas requisições. Tente novamente em instantes."
            }
          }
        }
      }
    },
    "schemas": {
      "TokenRequest": {
        "type": "object",
        "description": "A API key entra como client_secret (preferido) ou client_id. grant_type é ignorado.",
        "properties": {
          "client_secret": {
            "type": "string",
            "description": "A API key pk_live_... (preferido)."
          },
          "client_id": {
            "type": "string",
            "description": "Alternativa ao client_secret (mesma API key)."
          },
          "grant_type": {
            "type": "string",
            "description": "Ignorado pelo handler.",
            "example": "client_credentials"
          }
        }
      },
      "TokenResponse": {
        "type": "object",
        "required": [
          "access_token",
          "token_type",
          "expires_in",
          "scope"
        ],
        "properties": {
          "access_token": {
            "type": "string",
            "description": "É a própria API key enviada."
          },
          "token_type": {
            "type": "string",
            "const": "Bearer"
          },
          "expires_in": {
            "type": "integer",
            "description": "Fixo 86400 (cosmético; a validade real é a da chave).",
            "example": 86400
          },
          "scope": {
            "type": "string",
            "description": "Escopos da chave, separados por espaço.",
            "example": "products sales stats"
          }
        }
      },
      "OAuthError": {
        "type": "object",
        "properties": {
          "error": {
            "type": "string",
            "enum": [
              "invalid_request",
              "invalid_client"
            ]
          },
          "error_description": {
            "type": "string"
          }
        }
      },
      "AccountDetails": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "legal_name": {
            "type": [
              "string",
              "null"
            ]
          },
          "document": {
            "type": [
              "string",
              "null"
            ],
            "description": "CPF/CNPJ do produtor."
          },
          "phone": {
            "type": [
              "string",
              "null"
            ]
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "scopes": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "Escopos da chave usada."
          }
        }
      },
      "Product": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "pattern": "^[ABCDEFGHJKMNPQRSTUVWXYZ2-9]{6}$",
            "example": "K7M3Q9",
            "description": "ID curto do produto: o mesmo do navegador (/produtos/id/K7M3Q9) e o que os apps pedem."
          },
          "uuid": {
            "type": "string",
            "format": "uuid",
            "description": "Identificador longo (formato anterior)."
          },
          "name": {
            "type": "string"
          },
          "slug": {
            "type": "string"
          },
          "status": {
            "type": "string",
            "enum": [
              "publicado",
              "rascunho",
              "arquivado"
            ]
          },
          "type": {
            "type": "string",
            "enum": [
              "curso",
              "ebook",
              "mentoria",
              "software",
              "assinatura"
            ]
          },
          "description": {
            "type": [
              "string",
              "null"
            ]
          },
          "delivery": {
            "type": "array",
            "items": {
              "type": "string",
              "enum": [
                "pearfy_members",
                "external",
                "email_access",
                "payment_only"
              ]
            },
            "description": "Formas de entrega ativas do produto. Vazio = ainda nao configurada. `payment_only` e exclusivo: quando presente, e o unico item.",
            "examples": [
              [
                "pearfy_members",
                "email_access"
              ]
            ]
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "ProductCreate": {
        "type": "object",
        "required": [
          "name",
          "price"
        ],
        "properties": {
          "name": {
            "type": "string",
            "minLength": 2,
            "maxLength": 120,
            "description": "Nome do produto."
          },
          "price": {
            "type": "integer",
            "minimum": 1,
            "maximum": 9999900,
            "description": "Preço da oferta padrão em CENTAVOS."
          },
          "type": {
            "type": "string",
            "enum": [
              "curso",
              "ebook",
              "mentoria",
              "software",
              "assinatura"
            ],
            "default": "curso"
          },
          "description": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 2000
          },
          "payment_type": {
            "type": "string",
            "enum": [
              "unico",
              "assinatura"
            ],
            "description": "Se 'assinatura', o produto vira assinatura."
          },
          "recurrence": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "monthly",
              "quarterly",
              "semiannual",
              "annual",
              null
            ],
            "description": "Só se assinatura; default 'monthly'."
          }
        }
      },
      "ProductUpdate": {
        "type": "object",
        "description": "Todos os campos sao opcionais. status=publicado dispara os gates de completude + KYC. Mexer na entrega de um produto JA publicado sem enviar status reavalia a completude e pode REBAIXAR pra rascunho (ver `unpublished` na resposta).",
        "properties": {
          "name": {
            "type": "string",
            "minLength": 2,
            "maxLength": 120
          },
          "description": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 2000
          },
          "type": {
            "type": "string",
            "enum": [
              "curso",
              "ebook",
              "mentoria",
              "software",
              "assinatura"
            ]
          },
          "status": {
            "type": "string",
            "enum": [
              "publicado",
              "rascunho",
              "arquivado"
            ]
          },
          "delivery_url": {
            "type": [
              "string",
              "null"
            ],
            "format": "uri",
            "maxLength": 600
          },
          "delivery_instructions": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 2000
          },
          "delivery_types": {
            "type": "array",
            "items": {
              "type": "string",
              "enum": [
                "pearfy_members",
                "external",
                "email_access",
                "payment_only"
              ]
            },
            "minItems": 1,
            "description": "Substitui as formas de entrega do produto. Array vazio e recusado com 422. `payment_only` e exclusivo: enviado junto com outros, ele elimina os demais.",
            "examples": [
              [
                "pearfy_members",
                "email_access"
              ]
            ]
          }
        }
      },
      "Offer": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "product_id": {
            "type": "string",
            "example": "K7M3Q9",
            "description": "ID curto do produto."
          },
          "name": {
            "type": [
              "string",
              "null"
            ]
          },
          "code": {
            "type": [
              "string",
              "null"
            ],
            "description": "Código do checkout (null em ofertas criadas via API)."
          },
          "checkout_url": {
            "type": [
              "string",
              "null"
            ],
            "description": "https://pay.pearfy.com/{code} quando há code; senão null."
          },
          "price": {
            "type": "integer",
            "description": "Preço em CENTAVOS."
          },
          "currency": {
            "type": "string",
            "const": "BRL"
          },
          "payment_methods": {
            "type": "array",
            "items": {
              "type": "string",
              "enum": [
                "pix",
                "credit_card",
                "boleto"
              ]
            }
          },
          "installments_max": {
            "type": "integer"
          },
          "is_default": {
            "type": "boolean"
          },
          "active": {
            "type": "boolean"
          },
          "recurrence": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "monthly",
              "quarterly",
              "semiannual",
              "annual",
              null
            ]
          },
          "recurrence_limit": {
            "type": [
              "integer",
              "null"
            ]
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "product_uuid": {
            "type": "string",
            "format": "uuid",
            "description": "Identificador longo do produto (formato anterior)."
          }
        }
      },
      "OfferCreate": {
        "type": "object",
        "required": [
          "price"
        ],
        "properties": {
          "price": {
            "type": "integer",
            "minimum": 1,
            "maximum": 9999900,
            "description": "Preço em CENTAVOS."
          },
          "name": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 80
          },
          "payment_methods": {
            "type": "array",
            "items": {
              "type": "string",
              "enum": [
                "pix",
                "card",
                "boleto"
              ]
            },
            "minItems": 1,
            "default": [
              "pix",
              "card",
              "boleto"
            ],
            "description": "Na entrada, cartão é 'card' (na saída vira 'credit_card')."
          },
          "installments_max": {
            "type": "integer",
            "minimum": 1,
            "maximum": 12,
            "default": 12
          },
          "recurrence_period": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "monthly",
              "quarterly",
              "semiannual",
              "annual",
              null
            ],
            "description": "Torna a oferta recorrente."
          },
          "recurrence_limit": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 2,
            "maximum": 120,
            "description": "Só aplicado se recurrence_period presente."
          },
          "is_default": {
            "type": "boolean",
            "description": "Se true, desmarca is_default das outras ofertas."
          }
        }
      },
      "OfferUpdate": {
        "type": "object",
        "description": "Todos opcionais. recurrence_period NÃO é editável. is_default=false é ignorado.",
        "properties": {
          "name": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 80
          },
          "price": {
            "type": "integer",
            "minimum": 1,
            "maximum": 9999900,
            "description": "CENTAVOS."
          },
          "payment_methods": {
            "type": "array",
            "items": {
              "type": "string",
              "enum": [
                "pix",
                "card",
                "boleto"
              ]
            },
            "minItems": 1
          },
          "installments_max": {
            "type": "integer",
            "minimum": 1,
            "maximum": 12
          },
          "recurrence_limit": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 2,
            "maximum": 120
          },
          "is_default": {
            "type": "boolean",
            "description": "Só true tem efeito."
          },
          "active": {
            "type": "boolean"
          }
        }
      },
      "Sale": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "reference": {
            "type": "string",
            "description": "gateway_payment_id, ou o id do pedido se ausente."
          },
          "status": {
            "type": "string",
            "enum": [
              "paid",
              "waiting_payment",
              "refused",
              "refunded",
              "chargedback"
            ]
          },
          "payment_method": {
            "type": "string",
            "enum": [
              "pix",
              "credit_card",
              "boleto"
            ]
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          },
          "approved_date": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "refunded_at": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "currency": {
            "type": "string",
            "const": "BRL"
          },
          "charge_amount": {
            "type": "integer",
            "description": "Valor cobrado em CENTAVOS."
          },
          "net_amount": {
            "type": [
              "integer",
              "null"
            ],
            "description": "Líquido do produtor em CENTAVOS."
          },
          "product": {
            "type": "object",
            "description": "Produto da venda. No detalhe também traz name.",
            "properties": {
              "id": {
                "type": "string",
                "example": "K7M3Q9",
                "description": "ID curto do produto."
              },
              "uuid": {
                "type": "string",
                "format": "uuid"
              },
              "name": {
                "type": "string"
              }
            }
          },
          "customer": {
            "type": "object",
            "properties": {
              "name": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "email": {
                "type": "string"
              },
              "cpf": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "mobile": {
                "type": [
                  "string",
                  "null"
                ]
              }
            }
          }
        }
      },
      "RefundResponse": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "status": {
            "type": "string",
            "const": "refunded"
          }
        }
      },
      "Stats": {
        "type": "object",
        "properties": {
          "period": {
            "type": "object",
            "properties": {
              "start_date": {
                "type": "string",
                "format": "date-time"
              },
              "end_date": {
                "type": "string",
                "format": "date-time"
              }
            }
          },
          "orders_count": {
            "type": "integer",
            "description": "Total de pedidos no período (todos os status)."
          },
          "sales_count": {
            "type": "integer",
            "description": "Pedidos aprovados."
          },
          "refunded_count": {
            "type": "integer",
            "description": "Pedidos reembolsados."
          },
          "gross_amount": {
            "type": "integer",
            "description": "Bruto dos aprovados em BRL, em CENTAVOS. Vendas em outra moeda ficam em by_currency."
          },
          "net_amount": {
            "type": "integer",
            "description": "Líquido dos aprovados em BRL, em CENTAVOS. Vendas em outra moeda ficam em by_currency."
          },
          "currency": {
            "type": "string",
            "const": "BRL",
            "description": "Moeda de gross_amount e net_amount (sempre BRL)."
          },
          "by_currency": {
            "type": "object",
            "description": "Totais por moeda (código ISO-4217, BRL incluso), sem conversão: cada valor em centavos (minor units) da própria moeda.",
            "additionalProperties": {
              "$ref": "#/components/schemas/StatsCurrencyTotals"
            }
          }
        }
      },
      "StatsCurrencyTotals": {
        "type": "object",
        "properties": {
          "orders_count": {
            "type": "integer",
            "description": "Pedidos na moeda (todos os status)."
          },
          "sales_count": {
            "type": "integer",
            "description": "Pedidos aprovados na moeda."
          },
          "refunded_count": {
            "type": "integer",
            "description": "Pedidos reembolsados na moeda."
          },
          "gross_amount": {
            "type": "integer",
            "description": "Bruto dos aprovados, em centavos da moeda."
          },
          "net_amount": {
            "type": "integer",
            "description": "Líquido dos aprovados, em centavos da moeda."
          }
        }
      },
      "Pagination": {
        "type": "object",
        "properties": {
          "page_size": {
            "type": "integer"
          },
          "page_number": {
            "type": "integer"
          },
          "count": {
            "type": "integer",
            "description": "Total exato de registros."
          }
        }
      },
      "ListEnvelope": {
        "type": "object",
        "description": "Envelope de lista paginada.",
        "properties": {
          "object": {
            "type": "string",
            "const": "list"
          },
          "pagination": {
            "$ref": "#/components/schemas/Pagination"
          },
          "data": {
            "type": "array",
            "items": {}
          }
        }
      },
      "DeletedResponse": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string"
          },
          "deleted": {
            "type": "boolean",
            "const": true
          }
        }
      },
      "Error": {
        "type": "object",
        "required": [
          "error"
        ],
        "properties": {
          "error": {
            "type": "string",
            "description": "Código curto do erro."
          },
          "required": {
            "type": "string",
            "description": "Escopo exigido (em insufficient_scope)."
          },
          "detail": {
            "type": "string",
            "description": "Mensagem legível (validação/negócio)."
          },
          "message": {
            "type": "string",
            "description": "Mensagem legível (refund/gateway)."
          }
        }
      }
    }
  }
}
