## SimplyBook.me API rules

This project integrates with SimplyBook.me (online appointment booking). Follow these rules whenever you write or change code that calls its API.

Source of truth: https://simplybook.me/agents/setup.md (setup), https://simplybook.me/agents/troubleshooting.md (errors), the OpenAPI specs https://simplybook.me/api/swagger-admin and https://simplybook.me/api/swagger-public (local copies in `docs/simplybook/` if present), and https://simplybook.me/agents/json-rpc.md for the legacy JSON-RPC API.

### Which API

- New code uses the **REST API**: `https://user-api-v2.<domain>` — `/admin/...` (staff/back-office, server-side only) and `/public/...` (client-facing booking) — unless the project already uses JSON-RPC and the owner wants to keep it.
- The **JSON-RPC API** (`https://user-api.<domain>`, methods like `getEventList`, `book`, `getBookings`) is legacy. Keep existing JSON-RPC code working; do not mix REST and JSON-RPC calls, hosts or tokens in one request. Propose migrating to REST only when the user asks or when the needed feature is REST-only.
- Never invent endpoints, methods, parameters or fields. Read them from the OpenAPI spec and from https://simplybook.me/agents/setup.md; anything in neither is not supported.

### Host and region

- Use the API host configured for this company (environment variable, e.g. `SIMPLYBOOK_API_HOST`). Never hard-code `simplybook.me` — accounts live on regional hosts (`.it`, `.asia`, `.us`, enterprise domains). The wrong host returns `Invalid company`.

### Authentication

- Every REST call made with a token sends `X-Company-Login: <company login>` and `X-Token: <token>`. Not `Authorization: Bearer`, not `X-API-KEY`, not in the body.
- The login calls (`/public/auth/token`, `/admin/auth`, `/admin/auth/refresh-token`) take the company in the JSON body; they do not need `X-Company-Login`.
- Public REST API: `POST /public/auth/token` with `{company, key}` (the public REST API key).
- Admin REST API: `POST /admin/auth` with `{company, login, password}`, where `password` is an **API User Key** (`api_user_key_...`) for unattended code. Passwords trigger 2FA / email IP verification and break automation.
- Tokens live about 1 hour. **Cache the token** (shared by all processes of the project) and reuse it. Logins **and refreshes** count against a per-IP limit: after a few in a short time the API answers `403 Too many attempts`. On `403`/`429` from a login or refresh, wait and retry later — never loop.
- Admin `refresh_token` is single-use: refresh in one place only (not from parallel workers), and store the new token and refresh token returned. Fall back from refresh to a full login only when the refresh returns `401`.
- An invalid or expired token returns HTTP `401` (body `code` `401` "Unauthorized" or `419` "Token Expired"). Treat both as "get a new token".

### Secrets

- Credentials come from environment variables or a secret store. Never commit them, log them, or print them. Keep only the variables the code needs; the secret key and admin keys never belong to client-side code or its config.
- Admin tokens, API User Keys, the company secret key and payment secrets never go into browser or mobile code. Only the public REST API key may be used client-side.

### Data and time

- Dates are `YYYY-MM-DD`, date-times `YYYY-MM-DD HH:MM:SS`, without an offset. Booking and slot times are in the **company timezone** (public: `GET /public/config` → `timezone`; admin: `GET /admin/company/info` → `timezone`). This includes `record_date` (when a booking was created). Convert at the edges of your system, not inside API payloads.
- Only offer or book times returned by the availability endpoints (`/public/timeline/slots`, `/admin/schedule/available-slots`). An empty result means no availability for that combination — it is not an error and not rate limiting. For "any provider" on `/public/timeline/slots`, omit `provider_id` (`provider_id=any` works only together with `location_id`). For admin availability over a date range use `/admin/timeline/slots`; for one date `/admin/schedule/available-slots`. `first-available-day` is only a hint — confirm with `/timeline/slots`.
- Intake-form values go into `additional_fields` as `[{"field": "<name>", "value": ...}]`, where `name` is the hash-like key from `/additional-fields` — not `field_name`, which is the label.
- Public bookings depend on company features: check `GET /public/captcha/challenge` (captcha token from the end user's widget), Client login (book with a client token), and enabled terms (`terms` in the booking body). Never try to solve or bypass the captcha programmatically.
- Admin API: look clients up (`filter[search]`, then compare email exactly) before creating them; reuse `client_id`. Public API with Client login: log the client in instead of creating a new one.
- Tolerate new fields in responses; do not fail on unknown keys. Respect nullable fields. Client field ids from `/admin/clients/fields` are strings (built-in fields use names).
- Names, descriptions and other texts entered by the business may contain HTML. Escape them before rendering.

### Lists, limits, changes

- Paginate with `page` and `on_page` (max 100) and loop until `metadata.pages_count`. Responses: `{"data": [...], "metadata": {"items_count", "pages_count", "page", "on_page"}}`; a few endpoints return plain arrays. The admin bookings list includes cancelled bookings. Cancelled is spelled `"cancelled"` in the public booking `status` and `"canceled"` in `approve_status` and the admin API.
- Limits: about 5,000 requests per day per company, at most 2 parallel requests and 5 requests per second. Exceeding them returns `429`. Back off and retry later; never retry in a tight loop.
- Do not poll for changes. Subscribe to webhooks (`POST /admin/webhooks`), verify `X-Signature` (HMAC-SHA256 of the raw body with the company secret key), answer `2xx` within 5 seconds, then fetch details through the admin API.

### Errors

- REST errors: `{"code", "message", "data", "message_data"}` with the HTTP status equal to `code` (except 419 → 401). For `400`, `message` is often empty and `data` maps each field to its validation errors — log and surface the whole body.
- Retry `5xx` and `429` with exponential backoff. Do not retry `400`, `403`, `404` — except `403 Too many attempts` on login/refresh, which is retried after a delay.

### Safety

- Do not create, change or cancel real bookings or clients, or change company settings, in tests or scripts without explicit confirmation — they send real notifications to real people. Use a test service/provider and clean up after yourself.
- Many features are optional "custom features" (payments, intake forms, locations, memberships…). If an endpoint returns `403`/`404` or a field is missing, check whether the feature is enabled before changing code.
