{
  "openapi": "3.0.3",
  "info": {
    "title": "Setter AI API",
    "description": "API for Setter AI appointment booking assistant",
    "version": "1.0.0",
    "contact": {
      "email": "support@trysetter.com"
    }
  },
  "servers": [
    {
      "url": "https://chat.trysetter.com",
      "description": "Production server"
    }
  ],
  "security": [
    {
      "bearerAuth": []
    }
  ],
  "components": {
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "description": "Bearer token authentication using your API key"
      },
      "signatureAuth": {
        "type": "apiKey",
        "in": "header",
        "name": "X-Setter-Signature",
        "description": "HMAC-SHA256 signature of the raw request body, formatted as `sha256=<hex>`. Sign with any active org-level webhook signing key (manage them under Settings → Webhooks). Used by org webhook auth mode `hmac`."
      }
    },
    "schemas": {
      "BodyParameter": {
        "type": "object",
        "properties": {
          "type": {
            "type": "string",
            "enum": ["text"],
            "description": "Type of parameter"
          },
          "text": {
            "type": "string",
            "description": "Text content for the parameter"
          },
          "parameter_name": {
            "type": "string",
            "description": "Optional parameter name for template placeholder"
          }
        },
        "required": ["type", "text"]
      },
      "UpdateContactRequest": {
        "type": "object",
        "properties": {
          "id": {
            "type": "integer",
            "description": "Contact ID for direct lookup",
            "example": 123
          },
          "waId": {
            "type": "string",
            "description": "WhatsApp ID for contact lookup",
            "example": "1234567890"
          },
          "smsPhoneNumber": {
            "type": "string",
            "description": "SMS phone number for contact lookup",
            "example": "1234567890"
          },
          "firstName": {
            "type": "string",
            "description": "Contact's first name",
            "example": "John"
          },
          "lastName": {
            "type": "string",
            "description": "Contact's last name",
            "example": "Doe"
          },
          "fullName": {
            "type": "string",
            "description": "Contact's full name",
            "example": "John Doe"
          },
          "phoneNumber": {
            "type": "string",
            "description": "Contact's phone number",
            "example": "1234567890"
          },
          "email": {
            "type": "string",
            "format": "email",
            "description": "Contact's email address",
            "example": "john@example.com"
          },
          "defaultTimeZone": {
            "type": "string",
            "description": "Contact's default timezone",
            "example": "America/New_York"
          },
          "metadata": {
            "type": "object",
            "additionalProperties": {
              "type": "string"
            },
            "description": "Custom key-value pairs to store with the contact",
            "example": {
              "source": "website",
              "campaign": "summer2024"
            }
          }
        }
      },
      "Contact": {
        "type": "object",
        "properties": {
          "id": {
            "type": "integer",
            "description": "Contact ID",
            "example": 123
          },
          "createdAt": {
            "type": "string",
            "format": "date-time",
            "description": "Contact creation timestamp"
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time",
            "description": "Contact last update timestamp"
          },
          "firstName": {
            "type": "string",
            "description": "Contact's first name",
            "example": "John"
          },
          "lastName": {
            "type": "string",
            "description": "Contact's last name",
            "example": "Doe"
          },
          "fullName": {
            "type": "string",
            "description": "Contact's full name",
            "example": "John Doe"
          },
          "phoneNumber": {
            "type": "string",
            "description": "Contact's phone number",
            "example": "1234567890"
          },
          "waId": {
            "type": "string",
            "description": "WhatsApp ID",
            "example": "1234567890"
          },
          "smsPhoneNumber": {
            "type": "string",
            "description": "SMS phone number",
            "example": "1234567890"
          },
          "email": {
            "type": "string",
            "format": "email",
            "description": "Contact's email address",
            "example": "john@example.com"
          },
          "defaultTimeZone": {
            "type": "string",
            "description": "Contact's default timezone",
            "example": "America/New_York"
          },
          "metadata": {
            "type": "object",
            "additionalProperties": {
              "type": "string"
            },
            "description": "Custom key-value pairs stored with the contact"
          }
        }
      },
      "UpdateContactResponse": {
        "type": "object",
        "properties": {
          "data": {
            "$ref": "#/components/schemas/Contact"
          },
          "message": {
            "type": "string",
            "description": "Status message",
            "example": "Contact updated successfully"
          }
        }
      },
      "SendMessageRequest": {
        "type": "object",
        "properties": {
          "phoneNumber": {
            "type": "string",
            "description": "Contact's phone number in international format",
            "example": "1234567890"
          },
          "templateName": {
            "type": "string",
            "description": "Name of the WhatsApp message template (WhatsApp only)",
            "example": "hello_world"
          },
          "language": {
            "type": "string", 
            "description": "Language code for the template (WhatsApp only)",
            "example": "en_US"
          },
          "bodyParameters": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/BodyParameter"
            },
            "description": "Parameters to fill template placeholders (WhatsApp only)"
          },
          "message": {
            "type": "string",
            "description": "The message text to send (SMS/Twilio only)",
            "example": "Hello! I'm here to help you schedule an appointment."
          },
          "email": {
            "type": "string",
            "format": "email",
            "description": "Contact's email address",
            "example": "john@example.com"
          },
          "firstName": {
            "type": "string",
            "description": "Contact's first name",
            "example": "John"
          },
          "lastName": {
            "type": "string",
            "description": "Contact's last name", 
            "example": "Doe"
          },
          "fullName": {
            "type": "string",
            "description": "Contact's full name",
            "example": "John Doe"
          },
          "timeZone": {
            "type": "string",
            "description": "Contact's timezone",
            "example": "America/New_York"
          },
          "metadata": {
            "type": "object",
            "additionalProperties": {
              "type": "string"
            },
            "description": "Custom key-value pairs to store with the contact",
            "example": {
              "source": "website",
              "campaign": "summer2024"
            }
          },
          "calendarIntegrationId": {
            "type": "integer",
            "description": "ID of calendar integration to use for this conversation",
            "example": 123
          }
        },
        "required": ["phoneNumber"]
      },
      "ErrorResponse": {
        "type": "object",
        "properties": {
          "message": {
            "type": "string",
            "description": "Error message"
          }
        }
      },
      "AudienceFilterLead": {
        "type": "object",
        "description": "Lead identifier. Provide externalId, phoneE164, or both — externalId takes precedence when both match.",
        "properties": {
          "externalId": {
            "type": "string",
            "description": "Matches `external_id` from the audience CSV (case-sensitive)."
          },
          "phoneE164": {
            "type": "string",
            "description": "E.164 phone number (with leading `+`). Matches the normalized phone on the audience lead."
          }
        }
      },
      "AudienceFilterRequest": {
        "type": "object",
        "required": ["campaignId", "sendId", "mode", "leads"],
        "properties": {
          "campaignId": {
            "type": "integer",
            "description": "Campaign that owns the targeted send."
          },
          "sendId": {
            "type": "integer",
            "description": "Send to filter. Must currently be in `pending` status with `audienceFilterMode = webhook_filtered`."
          },
          "mode": {
            "type": "string",
            "enum": ["include", "exclude"],
            "description": "`include` — send only to listed leads. `exclude` — send to everyone EXCEPT listed leads."
          },
          "leads": {
            "type": "array",
            "minItems": 1,
            "maxItems": 100000,
            "items": { "$ref": "#/components/schemas/AudienceFilterLead" }
          }
        }
      },
      "AudienceFilterResponse": {
        "type": "object",
        "properties": {
          "status": {
            "type": "string",
            "enum": ["accepted", "already_received"],
            "description": "`accepted` on first delivery; `already_received` if this exact payload was already recorded for this send."
          },
          "leadCount": {
            "type": "integer",
            "description": "Count of leads in the accepted payload (omitted on `already_received`)."
          }
        }
      },
      "LeadEvent": {
        "type": "object",
        "required": ["phoneE164", "occurredAt"],
        "properties": {
          "phoneE164": {
            "type": "string",
            "description": "Recipient phone (E.164, with or without leading `+` — normalized via libphonenumber)."
          },
          "occurredAt": {
            "type": "string",
            "format": "date-time",
            "description": "ISO 8601 timestamp of when the event happened. Used by sends configured with a `within.minutes` window."
          },
          "metadata": {
            "type": "object",
            "description": "Optional metadata for your own records (≤ 8 KB encoded). Not interpreted by the filter logic.",
            "additionalProperties": true
          }
        }
      },
      "LeadEventsRequest": {
        "type": "object",
        "required": ["organizationId", "eventType", "events"],
        "properties": {
          "organizationId": {
            "type": "integer",
            "description": "Your Setter organization ID. Auth credentials must match this org."
          },
          "eventType": {
            "type": "string",
            "maxLength": 128,
            "description": "Free string scoped to your org. We recommend snake_case (e.g. `mastery_purchase`)."
          },
          "events": {
            "type": "array",
            "minItems": 1,
            "maxItems": 50000,
            "items": { "$ref": "#/components/schemas/LeadEvent" }
          }
        }
      },
      "LeadEventsResponse": {
        "type": "object",
        "properties": {
          "status": {
            "type": "string",
            "enum": ["accepted"]
          },
          "received": {
            "type": "integer",
            "description": "Number of entries in the input `events` array."
          },
          "inserted": {
            "type": "integer",
            "description": "Newly stored rows."
          },
          "duplicates": {
            "type": "integer",
            "description": "Entries that collided with an existing `(organizationId, phoneE164, eventType, occurredAt)` row."
          },
          "rejected": {
            "type": "integer",
            "description": "Entries that failed validation (bad phone, invalid date, oversize metadata)."
          },
          "rejects": {
            "type": "array",
            "description": "First 50 rejected entries with a reason (debugging aid).",
            "items": {
              "type": "object",
              "properties": {
                "index": { "type": "integer" },
                "reason": { "type": "string" }
              }
            }
          }
        }
      },
      "CreateBookingRequest": {
        "type": "object",
        "required": ["bot_id", "start_time"],
        "properties": {
          "bot_id": {
            "type": "integer",
            "description": "The bot this booking is for. Find the id in the dashboard URL.",
            "example": 700
          },
          "phone": {
            "type": "string",
            "description": "Contact's phone number. Accepted with or without leading `+` and separators (parsed via libphonenumber). Provide either `phone` or `wa_id`.",
            "example": "+447813194799"
          },
          "wa_id": {
            "type": "string",
            "description": "WhatsApp ID of the contact. Use this instead of `phone` if you have it. If both are provided, `wa_id` is tried first.",
            "example": "447813194799"
          },
          "start_time": {
            "type": "string",
            "format": "date-time",
            "description": "ISO 8601 timestamp of the appointment start.",
            "example": "2026-05-25T14:00:00Z"
          },
          "end_time": {
            "type": "string",
            "format": "date-time",
            "description": "ISO 8601 timestamp of the appointment end. Must be after `start_time`.",
            "example": "2026-05-25T15:00:00Z"
          },
          "time_zone": {
            "type": "string",
            "description": "IANA time zone (e.g. `Europe/London`).",
            "example": "Europe/London"
          },
          "source": {
            "type": "string",
            "description": "Free-form provenance tag. Defaults to `manual`.",
            "example": "calendly"
          },
          "external_id": {
            "type": "string",
            "description": "Stable id from your system used to deduplicate retries. Unique key is `(organization_id, source, external_id)`.",
            "example": "calendly-invitee-abc"
          },
          "default_country": {
            "type": "string",
            "description": "ISO 3166-1 alpha-2 country code (e.g. `GB`). Used to disambiguate national-format phone numbers.",
            "example": "GB"
          },
          "metadata": {
            "type": "object",
            "description": "Arbitrary JSON stored alongside the booking.",
            "additionalProperties": true,
            "example": {
              "invitee_email": "lead@example.com",
              "calendly_event_uri": "https://api.calendly.com/scheduled_events/abc"
            }
          }
        }
      },
      "CreateBookingResponse": {
        "type": "object",
        "properties": {
          "id": { "type": "integer", "example": 555 },
          "event_id": { "type": "integer", "example": 999 },
          "bot_id": { "type": "integer", "example": 700 },
          "contact_id": { "type": "integer", "example": 42 },
          "source": { "type": "string", "example": "calendly" },
          "external_id": { "type": "string", "nullable": true, "example": "calendly-invitee-abc" },
          "start_time": { "type": "string", "format": "date-time", "example": "2026-05-25T14:00:00.000Z" },
          "end_time": { "type": "string", "format": "date-time", "nullable": true, "example": "2026-05-25T15:00:00.000Z" },
          "time_zone": { "type": "string", "nullable": true, "example": "Europe/London" },
          "deduplicated": {
            "type": "boolean",
            "description": "`true` when an `external_id` collision returned the existing record instead of creating a new one.",
            "example": false
          }
        }
      },
      "CancelBookingResponse": {
        "type": "object",
        "properties": {
          "id": { "type": "integer", "example": 555 },
          "event_id": { "type": "integer", "example": 999 },
          "cancelled_at": { "type": "string", "format": "date-time", "example": "2026-05-20T17:42:00.000Z" }
        }
      }
    }
  },
  "paths": {
    "/api/v1/bot-integrations/{botIntegrationId}/conversations": {
      "get": {
        "summary": "Get Conversation History",
        "description": "Retrieve the full message history for a specific contact's conversation with a bot integration. Returns all messages in chronological order along with delivery statuses.\n\n**Platform-specific parameters:**\n- WhatsApp / SMS: provide `userNumber`\n- Playground / Embed: provide `sessionId`",
        "operationId": "getConversationHistory",
        "tags": ["Conversations"],
        "parameters": [
          {
            "name": "botIntegrationId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "integer"
            },
            "description": "The ID of your bot integration",
            "example": 123
          },
          {
            "name": "userNumber",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            },
            "description": "The contact's phone number (WhatsApp or SMS integrations)",
            "example": "1234567890"
          },
          {
            "name": "sessionId",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer"
            },
            "description": "The session ID (Playground or Embed integrations)",
            "example": 456
          }
        ],
        "responses": {
          "200": {
            "description": "Conversation history retrieved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "data": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "botIntegrationId": { "type": "integer", "example": 123 },
                          "content": { "type": "string", "example": "Hi! I'd like to book an appointment." },
                          "senderType": { "type": "string", "enum": ["user", "bot"], "example": "user" },
                          "createdAt": { "type": "string", "format": "date-time", "example": "2024-01-15T14:30:00.000Z" },
                          "messageId": { "type": "integer", "example": 789 },
                          "platformResourceId": { "type": "string", "example": "wamid.abc123" },
                          "latestStatus": { "type": "string", "nullable": true, "example": "delivered" },
                          "failureReason": { "type": "string", "nullable": true, "example": null },
                          "errorCode": { "type": "integer", "nullable": true, "example": null },
                          "errorTitle": { "type": "string", "nullable": true, "example": null },
                          "errorMessage": { "type": "string", "nullable": true, "example": null },
                          "errorDetails": { "type": "string", "nullable": true, "example": null }
                        }
                      }
                    },
                    "metadata": {
                      "type": "object",
                      "properties": {
                        "contextStartsAt": {
                          "type": "string",
                          "format": "date-time",
                          "nullable": true,
                          "description": "Timestamp from which the bot's active context begins (null if no reset has occurred)",
                          "example": "2024-01-15T12:00:00.000Z"
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Bad Request - missing required query parameter for the platform",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" },
                "example": { "message": "Bad Request - Missing user number" }
              }
            }
          },
          "401": {
            "description": "Unauthorized",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" },
                "example": { "message": "Unauthorized" }
              }
            }
          },
          "404": {
            "description": "Bot integration not found or access denied",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" },
                "example": { "message": "Not found" }
              }
            }
          }
        }
      }
    },
    "/api/v1/bot-integrations/{botIntegrationId}/messages/send": {
      "post": {
        "summary": "Send Message",
        "description": "Send a message to initiate a conversation with a contact. This endpoint supports both WhatsApp and SMS platforms and automatically creates contacts and conversations.\n\n**Rate Limiting**: You cannot send another bot-initiated message to the same phone number within 30 minutes.",
        "operationId": "sendMessage",
        "tags": ["Messages"],
        "parameters": [
          {
            "name": "botIntegrationId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "integer"
            },
            "description": "The ID of your bot integration",
            "example": 123
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SendMessageRequest"
              },
              "examples": {
                "whatsapp": {
                  "summary": "WhatsApp Template Message",
                  "value": {
                    "phoneNumber": "1234567890",
                    "templateName": "appointment_booking",
                    "language": "en_US",
                    "bodyParameters": [
                      {
                        "type": "text",
                        "text": "John",
                        "parameter_name": "customer_name"
                      }
                    ],
                    "email": "john@example.com",
                    "firstName": "John",
                    "lastName": "Doe",
                    "timeZone": "America/New_York"
                  }
                },
                "sms": {
                  "summary": "SMS Message",
                  "value": {
                    "phoneNumber": "1234567890",
                    "message": "Hi! I'm your AI assistant. How can I help you schedule an appointment today?",
                    "email": "jane@example.com",
                    "firstName": "Jane",
                    "lastName": "Smith",
                    "timeZone": "America/Los_Angeles",
                    "metadata": {
                      "source": "website_form",
                      "page": "/contact"
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Message sent successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "integer",
                  "example": 201
                }
              }
            }
          },
          "400": {
            "description": "Bad Request",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                },
                "examples": {
                  "missing_phone": {
                    "summary": "Missing phone number",
                    "value": {
                      "message": "Missing phone number"
                    }
                  },
                  "missing_message": {
                    "summary": "Missing message for SMS",
                    "value": {
                      "message": "Bad Request - message is required"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                },
                "example": {
                  "message": "Unauthorized"
                }
              }
            }
          },
          "403": {
            "description": "Forbidden",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                },
                "example": {
                  "message": "Forbidden"
                }
              }
            }
          },
          "429": {
            "description": "Rate limit exceeded",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                },
                "example": {
                  "message": "Error: Bot initiated message was already sent in the last 30 minutes"
                }
              }
            }
          },
          "500": {
            "description": "Internal Server Error",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": false
                    },
                    "error": {
                      "type": "string",
                      "example": "Internal server error occurred"
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/api/v1/bookings": {
      "post": {
        "summary": "Create Booking",
        "description": "Record an appointment that was booked outside of Setter (e.g. directly on your Calendly, a manual phone callback, or any other calendar tool). Once stored against a contact, the bot sees it on the next inbound message and will not ask the contact to book another appointment or send a booking link.\n\n**Contact matching** is performed in this order:\n1. Exact `wa_id` match (if `wa_id` is supplied)\n2. `wa_id` derived from `phone` (E.164 minus the leading `+`)\n3. `sms_phone_number` match (both with and without leading `+`)\n\nThe contact must already exist in Setter — bookings cannot create new contacts.\n\n**Bot scope:** a booking is only visible to the `bot_id` it was filed against. A bot that runs on multiple channels (e.g. WhatsApp + SMS) sees the same booking on both channels, but a separate bot owned by the same organization will not.\n\n**Idempotency:** if `external_id` is provided, the unique key `(organization_id, source, external_id)` makes retries safe. A re-POST with the same triple returns the existing booking with `deduplicated: true` and HTTP `200`.",
        "operationId": "createBooking",
        "tags": ["Bookings"],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/CreateBookingRequest" },
              "examples": {
                "by_phone": {
                  "summary": "Create by phone number",
                  "value": {
                    "bot_id": 700,
                    "phone": "+447813194799",
                    "start_time": "2026-05-25T14:00:00Z",
                    "end_time": "2026-05-25T15:00:00Z",
                    "time_zone": "Europe/London",
                    "source": "calendly",
                    "external_id": "calendly-invitee-abc"
                  }
                },
                "by_wa_id": {
                  "summary": "Create by WhatsApp ID",
                  "value": {
                    "bot_id": 700,
                    "wa_id": "447813194799",
                    "start_time": "2026-05-25T14:00:00Z",
                    "time_zone": "Europe/London",
                    "source": "manual"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Booking created",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/CreateBookingResponse" }
              }
            }
          },
          "200": {
            "description": "Idempotent replay — a booking with the same `(organization_id, source, external_id)` already existed and is returned with `deduplicated: true`.",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/CreateBookingResponse" },
                "example": {
                  "id": 555,
                  "event_id": 999,
                  "bot_id": 700,
                  "contact_id": 42,
                  "source": "calendly",
                  "external_id": "calendly-invitee-abc",
                  "start_time": "2026-05-25T14:00:00.000Z",
                  "end_time": null,
                  "time_zone": "Europe/London",
                  "deduplicated": true
                }
              }
            }
          },
          "400": {
            "description": "Validation error",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" },
                "examples": {
                  "missing_bot_id": { "value": { "message": "`bot_id` is required and must be a positive integer" } },
                  "missing_identifier": { "value": { "message": "Either `phone` or `wa_id` is required" } },
                  "invalid_phone": { "value": { "message": "`phone` could not be parsed" } },
                  "invalid_start_time": { "value": { "message": "`start_time` is not a valid ISO 8601 date" } },
                  "invalid_end_time": { "value": { "message": "`end_time` must be a valid date after `start_time`" } }
                }
              }
            }
          },
          "403": {
            "description": "Contact does not belong to your organization",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" },
                "example": { "message": "Contact does not belong to your organization" }
              }
            }
          },
          "404": {
            "description": "Bot or contact not found",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" },
                "examples": {
                  "bot_not_found": { "value": { "message": "`bot_id` not found in your organization" } },
                  "contact_not_found": { "value": { "message": "Contact not found for the supplied phone or wa_id" } }
                }
              }
            }
          }
        }
      }
    },
    "/api/v1/bookings/{id}/cancel": {
      "post": {
        "summary": "Cancel Booking",
        "description": "Soft-deletes a previously recorded booking. Use the `id` returned by [Create Booking](/setter-ai/bookings). The bot will stop seeing this booking in its context from the next message onwards.",
        "operationId": "cancelBooking",
        "tags": ["Bookings"],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "integer" },
            "description": "Booking id returned by Create Booking.",
            "example": 555
          }
        ],
        "responses": {
          "200": {
            "description": "Cancelled",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/CancelBookingResponse" }
              }
            }
          },
          "400": {
            "description": "Invalid booking id",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" },
                "example": { "message": "Invalid booking id" }
              }
            }
          },
          "404": {
            "description": "Booking not found (or not owned by your organization)",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" },
                "example": { "message": "Booking not found" }
              }
            }
          }
        }
      }
    },
    "/api/v1/contacts": {
      "put": {
        "summary": "Update Contact",
        "description": "Update an existing contact's information. You can identify the contact using either ID, WhatsApp ID (waId), or SMS phone number (smsPhoneNumber). Only one identifier is required, but at least one must be provided.\n\n**Important Notes:**\n- If multiple contacts match the identifier, the operation will fail with a 409 error\n- If no contacts are found, the operation will return a 404 error\n- Only contacts that your organization has access to can be updated\n- All fields except the identifier are optional and will only be updated if provided",
        "operationId": "updateContact",
        "tags": ["Contacts"],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateContactRequest"
              },
              "examples": {
                "update_by_id": {
                  "summary": "Update contact by ID",
                  "value": {
                    "id": 123,
                    "firstName": "John",
                    "lastName": "Smith",
                    "email": "john.smith@example.com",
                    "defaultTimeZone": "America/New_York",
                    "metadata": {
                      "source": "updated_via_api",
                      "last_interaction": "2024-01-15"
                    }
                  }
                },
                "update_by_whatsapp_id": {
                  "summary": "Update contact by WhatsApp ID",
                  "value": {
                    "waId": "1234567890",
                    "fullName": "Jane Doe",
                    "email": "jane.doe@example.com",
                    "defaultTimeZone": "America/Los_Angeles"
                  }
                },
                "update_by_sms_phone": {
                  "summary": "Update contact by SMS phone number",
                  "value": {
                    "smsPhoneNumber": "1234567890",
                    "firstName": "Alice",
                    "lastName": "Johnson",
                    "metadata": {
                      "source": "sms_campaign",
                      "campaign_id": "campaign_123"
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Contact updated successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UpdateContactResponse"
                },
                "example": {
                  "data": {
                    "id": 123,
                    "createdAt": "2024-01-01T10:00:00Z",
                    "updatedAt": "2024-01-15T14:30:00Z",
                    "firstName": "John",
                    "lastName": "Smith",
                    "fullName": "John Smith",
                    "phoneNumber": "1234567890",
                    "waId": "1234567890",
                    "smsPhoneNumber": "1234567890",
                    "email": "john.smith@example.com",
                    "defaultTimeZone": "America/New_York",
                    "metadata": {
                      "source": "updated_via_api",
                      "last_interaction": "2024-01-15"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Bad Request",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                },
                "examples": {
                  "missing_identifier": {
                    "summary": "Missing contact identifier",
                    "value": {
                      "message": "Either id, waId or smsPhoneNumber is required"
                    }
                  },
                  "invalid_email": {
                    "summary": "Invalid email format",
                    "value": {
                      "message": "Invalid email format"
                    }
                  },
                  "no_fields": {
                    "summary": "No updatable fields provided",
                    "value": {
                      "data": null,
                      "message": "No updatable fields provided"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                },
                "example": {
                  "message": "Unauthorized"
                }
              }
            }
          },
          "403": {
            "description": "Forbidden",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                },
                "example": {
                  "message": "Not authorized"
                }
              }
            }
          },
          "404": {
            "description": "Contact not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                },
                "example": {
                  "message": "No accessible contacts found"
                }
              }
            }
          },
          "409": {
            "description": "Multiple contacts found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                },
                "example": {
                  "message": "Multiple contacts matched; no update performed"
                }
              }
            }
          },
          "500": {
            "description": "Internal Server Error",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": false
                    },
                    "error": {
                      "type": "string",
                      "example": "Internal server error occurred"
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/api/v1/webhooks/campaigns/audience-filter": {
      "post": {
        "summary": "Filter Send Audience",
        "description": "Narrows a scheduled campaign send's audience to a real-time list of leads. POST an `include` or `exclude` list to a specific send up until 5 minutes before that send fires (the filter deadline).\n\n**Auth:** per-organization webhook auth — either a Bearer API key OR an HMAC-SHA256 signature over the raw body. Configure the mode under Settings → Webhooks.\n\n**Idempotency:** identical payload bodies are deduped per send via the SHA-256 of the body. A duplicate POST returns `{ status: 'already_received' }`.\n\n**Most-recent-wins:** if you POST multiple distinct filter events for the same `sendId` before the deadline, only the latest is applied at materialize time. Replace the entire list when updating; deltas are not supported.",
        "operationId": "submitAudienceFilter",
        "tags": ["Campaigns"],
        "security": [
          { "bearerAuth": [] },
          { "signatureAuth": [] }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/AudienceFilterRequest" },
              "examples": {
                "include_by_external_id": {
                  "summary": "Include only specific leads (by externalId)",
                  "value": {
                    "campaignId": 42,
                    "sendId": 137,
                    "mode": "include",
                    "leads": [
                      { "externalId": "your_lead_id_001" },
                      { "externalId": "your_lead_id_002" }
                    ]
                  }
                },
                "exclude_by_phone": {
                  "summary": "Exclude specific leads (by phoneE164)",
                  "value": {
                    "campaignId": 42,
                    "sendId": 137,
                    "mode": "exclude",
                    "leads": [
                      { "phoneE164": "+15551234567" },
                      { "phoneE164": "+15557654321" }
                    ]
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Filter event recorded (or duplicate of an earlier payload)",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/AudienceFilterResponse" },
                "examples": {
                  "accepted": {
                    "summary": "First delivery",
                    "value": { "status": "accepted", "leadCount": 12345 }
                  },
                  "already_received": {
                    "summary": "Identical payload replayed (no-op)",
                    "value": { "status": "already_received" }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Malformed body, missing required field, or unknown campaignId/sendId for this org",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" },
                "example": { "message": "Unknown campaignId / sendId" }
              }
            }
          },
          "401": {
            "description": "Auth failed — bad signature or invalid API key",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" },
                "example": { "message": "Invalid signature" }
              }
            }
          },
          "403": {
            "description": "Campaigns feature not enabled for this organization",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" },
                "example": { "message": "Forbidden" }
              }
            }
          },
          "409": {
            "description": "Filter deadline already passed, or send is no longer pending",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" },
                "examples": {
                  "deadline_passed": {
                    "summary": "Filter deadline elapsed (5 min before send)",
                    "value": { "error": "Filter deadline passed", "deadlineUtc": "2026-05-15T13:55:00Z" }
                  },
                  "send_not_pending": {
                    "summary": "Send already started materializing",
                    "value": { "error": "Send no longer pending", "status": "queued" }
                  }
                }
              }
            }
          },
          "413": {
            "description": "Payload exceeds 10 MB",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" },
                "example": { "message": "Payload too large" }
              }
            }
          }
        }
      }
    },
    "/api/v1/webhooks/lead-events": {
      "post": {
        "summary": "Send Lead Event",
        "description": "Generic per-phone event stream. Use this to record that a phone number did event X at time T, so future campaign sends can include or exclude that lead based on whether the event happened (optionally within a time window).\n\n**Typical event types:** `mastery_purchase`, `webinar_attended`, `trial_started`, `cart_abandoned`. You choose the names — they're free strings scoped to your organization.\n\n**Auth:** per-organization webhook auth — either a Bearer API key OR an HMAC-SHA256 signature over the raw body. Configure under Settings → Webhooks.\n\n**Idempotency:** the unique key `(organizationId, phoneE164, eventType, occurredAt)` makes retries safe. Re-POSTing the same batch returns `duplicates = received` and `inserted = 0`.\n\n**Validation:** invalid rows (bad phone, missing/invalid `occurredAt`, oversize metadata) are rejected per-row, not per-batch — you get a `rejects[]` array back rather than a 400 for the whole call.",
        "operationId": "submitLeadEvents",
        "tags": ["Campaigns"],
        "security": [
          { "bearerAuth": [] },
          { "signatureAuth": [] }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/LeadEventsRequest" },
              "examples": {
                "single_event": {
                  "summary": "Single event (real-time stream pattern)",
                  "value": {
                    "organizationId": 42,
                    "eventType": "mastery_purchase",
                    "events": [
                      {
                        "phoneE164": "+15551234567",
                        "occurredAt": "2026-05-12T18:34:00Z",
                        "metadata": { "orderId": "ord_9F2", "amountUsd": 297 }
                      }
                    ]
                  }
                },
                "bulk_batch": {
                  "summary": "Bulk batch (pre-aggregated snapshot)",
                  "value": {
                    "organizationId": 42,
                    "eventType": "webinar_attended",
                    "events": [
                      { "phoneE164": "+15551234567", "occurredAt": "2026-05-15T13:00:00Z" },
                      { "phoneE164": "+447700900123", "occurredAt": "2026-05-15T13:05:11Z" },
                      { "phoneE164": "+4915757956355", "occurredAt": "2026-05-15T13:08:30Z" }
                    ]
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Batch processed. Inspect `inserted` / `duplicates` / `rejected` for outcome detail.",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/LeadEventsResponse" },
                "examples": {
                  "all_new": {
                    "summary": "All entries new",
                    "value": {
                      "status": "accepted",
                      "received": 3,
                      "inserted": 3,
                      "duplicates": 0,
                      "rejected": 0,
                      "rejects": []
                    }
                  },
                  "mixed": {
                    "summary": "Some duplicates + some validation rejects",
                    "value": {
                      "status": "accepted",
                      "received": 5,
                      "inserted": 3,
                      "duplicates": 1,
                      "rejected": 1,
                      "rejects": [
                        { "index": 4, "reason": "invalid phoneE164" }
                      ]
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Malformed body, missing required field, or `events` array empty / over the 50000 cap",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" },
                "examples": {
                  "missing_field": {
                    "summary": "Required field missing",
                    "value": { "message": "eventType must be a non-empty string" }
                  },
                  "too_many_events": {
                    "summary": "Batch too large",
                    "value": { "message": "events cannot exceed 50000 entries" }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Auth failed — invalid API key or bad HMAC signature",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" },
                "example": { "message": "Invalid or missing API key" }
              }
            }
          },
          "403": {
            "description": "Campaigns feature not enabled for this organization",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" },
                "example": { "message": "Forbidden" }
              }
            }
          },
          "413": {
            "description": "Payload exceeds 10 MB",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" },
                "example": { "message": "Payload too large" }
              }
            }
          }
        }
      }
    }
  }
}
