openapi: 3.1.0
info:
  title: Peaceful Hire server API
  version: "1.0.0"
  description: |
    Server routes that need secrets or third-party providers. Most of the platform's
    functionality is exposed through Supabase (PostgREST and RPC functions) under row
    level security; see docs/CONVENTIONS.md for the RPC catalogue.

    Authentication: web clients send the Supabase session cookie; mobile clients send
    `Authorization: Bearer <Supabase access token>`.
servers:
  - url: /api/v1
paths:
  /health:
    get:
      summary: Liveness and database reachability
      responses:
        "200": { description: Healthy, content: { application/json: { schema: { $ref: "#/components/schemas/Health" } } } }
        "503": { description: Database unreachable }
  /auth/email-second-factor:
    post:
      summary: Email a one-time code and link to confirm the second step of the caller's password sign-in
      description: Alternative to an authenticator code for administrators. Only a session that signed in with a password can start it; limited to five emails per 15 minutes.
      security: [{ session: [] }, { bearer: [] }]
      responses:
        "200": { description: Email sent, content: { application/json: { schema: { type: object, properties: { challengeId: { type: string, format: uuid }, sentTo: { type: string, description: Masked address } } } } } }
        "400": { $ref: "#/components/responses/Error" }
        "401": { $ref: "#/components/responses/Error" }
        "429": { $ref: "#/components/responses/Error" }
  /auth/email-second-factor/verify:
    post:
      summary: Confirm the caller's session with the 6-digit code from the email
      security: [{ session: [] }, { bearer: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [challengeId, code], properties: { challengeId: { type: string, format: uuid }, code: { type: string, pattern: "^[0-9]{6}$" } } }
      responses:
        "200": { description: Confirmed; the session now counts as two-step verified }
        "400": { description: Wrong or expired code, content: { application/json: { schema: { type: object, properties: { error: { type: string }, attemptsLeft: { type: integer } } } } } }
        "401": { $ref: "#/components/responses/Error" }
  /auth/email-second-factor/link:
    post:
      summary: Confirm a challenge with the email sign-in tokens from the link in the email (any device)
      description: The tokens must come from an email one-time sign-in issued after the challenge. That email session is ended immediately.
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [challengeId, accessToken, refreshToken], properties: { challengeId: { type: string, format: uuid }, accessToken: { type: string }, refreshToken: { type: string } } }
      responses:
        "200": { description: Confirmed }
        "400": { $ref: "#/components/responses/Error" }
  /payments/checkout:
    post:
      summary: Start or resume a hosted checkout for a booking or a payable fee
      description: The amount is always taken from the database (booking terms snapshot or confirmed fee). A recent open intent is reused instead of creating a duplicate charge.
      security: [{ session: [] }, { bearer: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              oneOf:
                - { type: object, required: [bookingId], properties: { bookingId: { type: string, format: uuid } } }
                - { type: object, required: [feeId], properties: { feeId: { type: string, format: uuid } } }
      responses:
        "200": { description: Checkout created, content: { application/json: { schema: { type: object, properties: { checkoutUrl: { type: string }, transactionId: { type: string, format: uuid } } } } } }
        "400": { $ref: "#/components/responses/Error" }
        "401": { $ref: "#/components/responses/Error" }
        "502": { $ref: "#/components/responses/Error" }
  /payments/webhooks/{provider}:
    post:
      summary: Payment provider webhook
      description: The raw body signature is verified (Paystack HMAC-SHA512 `x-paystack-signature`; sandbox HMAC-SHA256 `x-sandbox-signature`). Events are processed idempotently; invalid signatures are logged and rejected.
      parameters:
        - { name: provider, in: path, required: true, schema: { type: string, enum: [paystack, sandbox] } }
      responses:
        "200": { description: Accepted }
        "401": { description: Invalid signature }
  /payments/sandbox/complete:
    post:
      summary: Simulate the outcome of a sandbox checkout (sandbox provider only)
      security: [{ session: [] }, { bearer: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [transactionId, outcome], properties: { transactionId: { type: string, format: uuid }, outcome: { type: string, enum: [succeeded, failed] } } }
      responses:
        "200": { description: Event processed }
        "409": { description: Payment no longer pending }
  /payouts/banks:
    get:
      summary: South African banks for payout accounts
      responses:
        "200": { description: Bank list, content: { application/json: { schema: { type: object, properties: { banks: { type: array, items: { type: object, properties: { name: { type: string }, code: { type: [string, "null"] } } } } } } } } }
  /payouts/account:
    post:
      summary: Save a worker's payout account
      description: The full account number is sent only to the payment provider to create a transfer recipient. Peaceful Hire stores the last four digits.
      security: [{ session: [] }, { bearer: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [holder, bankName, accountType, accountNumber]
              properties:
                holder: { type: string }
                bankName: { type: string }
                bankCode: { type: [string, "null"] }
                accountType: { type: string, enum: [cheque, savings, transmission] }
                accountNumber: { type: string, pattern: "^[0-9]{6,16}$" }
      responses:
        "200": { description: Saved, content: { application/json: { schema: { type: object, properties: { ok: { type: boolean }, verified: { type: boolean }, note: { type: string } } } } } }
  /admin/refunds/{id}/process:
    post:
      summary: Send an approved refund to the provider (finance.manage, MFA session)
      security: [{ session: [] }]
      parameters: [{ name: id, in: path, required: true, schema: { type: string, format: uuid } }]
      responses:
        "200": { description: Submitted, content: { application/json: { schema: { $ref: "#/components/schemas/ActionResult" } } } }
        "403": { description: Not permitted or MFA required }
        "409": { description: Refund not approved }
  /admin/payouts/{id}/process:
    post:
      summary: Submit an initiated payout to the provider (finance.manage, MFA session)
      security: [{ session: [] }]
      parameters: [{ name: id, in: path, required: true, schema: { type: string, format: uuid } }]
      responses:
        "200": { description: Submitted, content: { application/json: { schema: { $ref: "#/components/schemas/ActionResult" } } } }
        "403": { description: Not permitted or MFA required }
  /geocode:
    get:
      summary: Search South African addresses (OpenStreetMap Nominatim, cached)
      security: [{ session: [] }, { bearer: [] }]
      parameters: [{ name: q, in: query, required: true, schema: { type: string, minLength: 4 } }]
      responses:
        "200": { description: Results, content: { application/json: { schema: { type: object, properties: { results: { type: array, items: { type: object, properties: { label: { type: string }, lat: { type: number }, lng: { type: number }, suburb: { type: [string, "null"] }, city: { type: [string, "null"] } } } } } } } } }
  /internal/dispatch:
    post:
      summary: Deliver queued notifications (internal; called by the database scheduler and Vercel Cron)
      security: [{ internal: [] }]
      responses:
        "200": { description: Delivery summary, content: { application/json: { schema: { type: object, properties: { sent: { type: integer }, skipped: { type: integer }, failed: { type: integer } } } } } }
        "401": { description: Missing or wrong secret }
components:
  securitySchemes:
    session: { type: apiKey, in: cookie, name: sb-access-token, description: Supabase session cookie set by the web app }
    bearer: { type: http, scheme: bearer, description: Supabase access token (mobile app) }
    internal: { type: apiKey, in: header, name: x-internal-secret }
  responses:
    Error:
      description: Error with a plain-language message
      content: { application/json: { schema: { type: object, properties: { error: { type: string } } } } }
  schemas:
    Health:
      type: object
      properties:
        status: { type: string, enum: [ok, degraded] }
        database: { type: string }
        latencyMs: { type: integer }
        time: { type: string, format: date-time }
        version: { type: string }
    ActionResult:
      type: object
      properties:
        ok: { type: boolean }
        status: { type: string }
        error: { type: string }
