openapi: 3.0.3
info:
  title: MUDBASESDK
  description: >
    MUDBASE is a scalable, real-time, and secure Backend-as-a-Service (BaaS) platform 

    designed for modern applications. Built with custom logic, it offers fine-grained 

    control, extensibility, and enterprise-grade security.


    ## Features

    - 🔐 Multi-provider authentication (30+ OAuth providers)

    - 📊 Real-time database with collections

    - 📁 File storage and management

    - 🔑 API key management with permissions

    - 🔗 Webhook system with retry logic

    - ⚡ Serverless functions

    - 💬 Multi-channel messaging (Push, Email, SMS)

    - 📈 Usage analytics and monitoring

    - 🌐 Real-time WebSocket events

    - 🔍 Full-text search capabilities

    - 💳 Billing: fiat only for project subscriptions and org BaaS checkout (platform fee split). On-chain billing is
    not exposed on these APIs (optional `crypto-payment-module/` in repo, not mounted by default).

    - 🏢 Enterprise / Phase 4: custom domains on Growth, Scale, and Enterprise (TXT DNS at
    `_mudbase-verify.<hostname>`); `settings.customDomainAddon` is optional (billing/legacy); dedicated DB migration
    script, periodic DNS recheck job, optional `infrastructureEnvironments[]` and edge/metering fields on `dedicated`.
  version: 1.3.17
  contact:
    name: MUDBASE Support
    url: https://mudbase.dev/support
    email: support@mudbase.dev
  license:
    name: MIT
    url: https://opensource.org/licenses/MIT
servers:
  - url: https://cloud.mudbase.dev
    description: Production server
tags:
  - name: Authentication
    description: User authentication and authorization
  - name: Users
    description: User profile management
  - name: Organizations
    description: Organization and team management
  - name: Projects
    description: >
      Project management and configuration. GET /api/projects/{projectId}/dashboard/overview returns the full dashboard
      KPI bundle (usage, active users, org-wide uptime/latency, 14d volume, recent activity).
  - name: Collections
    description: Database schema and collection management
  - name: Data
    description: CRUD operations on collection data
  - name: Buckets
    description: Bucket management operations
  - name: Files
    description: File storage and management
  - name: API Keys
    description: API key management and permissions
  - name: Webhooks
    description: >
      **Outbound webhooks (Mudbase → your URL):** Configure a single callback URL per project with `PUT
      /api/webhooks/projects/{projectId}/config`.

      When events fire, Mudbase creates **delivery log** rows (`WebhookLog` in the database) and HTTP POSTs to your URL.


      **What is `webhookId` in the API?**

      - In **`POST /api/webhooks/trigger`** and **`POST /api/webhooks/retry/{webhookId}`**, the id is the **MongoDB
      `_id` of a webhook delivery log** document—not a separate “subscription id” from the config endpoint.

      - After **`POST /api/webhooks/trigger`**, the JSON field **`webhookId`** in the response is that log’s **`_id`**.
      Use the same value in the retry path to re-queue delivery.

      - List logs with **`GET /api/webhooks`** (org-wide) or **`GET /api/webhooks/projects/{projectId}`**
      (project-scoped); each row’s **`_id`** is what you pass to retry.

      - Each log also has an internal string field **`webhookId`** (e.g. `manual-173…`) used for correlation; you
      normally use the document **`_id`** for retry.
  - name: Functions
    description: Serverless function management
  - name: Messaging
    description: Push notifications, email, and SMS
  - name: Email
    description: >
      Project-scoped transactional email queue, templates, analytics, and BYO SMTP
      (`/api/projects/{projectId}/email/...`).


      ### Template `{{placeholders}}` rules


      - Placeholders use the form `{{variableName}}` (case-sensitive). Every name that appears in `subject`, `htmlBody`,
      or `textBody` must be listed in the request body **`variables`** array **without** braces (e.g. use `userName` for
      `{{userName}}`).

      - When sending with **`POST .../email/send`**, pass values in **`data`**. The worker merges `data` with **layout
      defaults** (branding, footer, year, etc. from `augmentTemplateData`).

      - **Outer email shell** (header logo, brand title, footer, “Powered by …” on free plan) is applied **after** your
      HTML is rendered. You normally do **not** put shell tokens inside `htmlBody`; they are filled by the platform
      around your content.


      ### Common placeholders (transactional / auth templates)


      **Identity & app:** `{{appName}}`, `{{appNameDisplay}}`, `{{userName}}`, `{{USER_NAME}}`, `{{USER_EMAIL}}`,
      `{{orgName}}`, `{{projectName}}`, `{{projectId}}`.


      **Links & actions:** `{{resetUrl}}`, `{{verificationUrl}}`, `{{invitationUrl}}`, `{{magicLinkUrl}}`,
      `{{paymentLink}}`, `{{CTA_URL}}`, `{{SECURITY_URL}}`, `{{PLATFORM_URL}}`.


      **Invites & roles:** `{{inviterName}}`, `{{role}}`.


      **OTP / expiry copy:** `{{otpCode}}`, `{{EXPIRY_MINUTES}}`, `{{expiresIn}}`.


      **Sign-in alerts:** `{{REQUEST_TIME}}`, `{{REQUEST_IP}}`.


      **Plans & account:** `{{planName}}`, `{{PLAN_NAME}}`, `{{JOIN_DATE}}`.


      **Usage & org limits:** `{{percent}}`, `{{resource}}`, `{{used}}`, `{{limit}}`, `{{cutOffNote}}`.


      **Overage & spend (org billing emails):** `{{amount}}`, `{{period}}`, `{{softLimit}}`, `{{hardLimit}}`,
      `{{threshold}}`.


      **Payout alerts:** `{{currency}}`, `{{errorMessage}}`, `{{collectedAmount}}`, `{{threshold}}` (along with
      `{{projectId}}` above).


      ### Layout / branding (injected around your body; optional to reference in custom HTML)


      Filled by the renderer when the shared layout wraps content: branding and footer context includes values such as
      **`BRAND_NAME`**, **`BRAND_INITIAL`**, **`LOGO_URL`**, **`primaryColor`**, **`senderLine`**, **`YEAR`**,
      **`PLATFORM_NAME`**, **`footerLine`**, **`POWERED_BY_PLATFORM`** (HTML fragment when shown). If you reference any
      of these **inside** your `subject` / `htmlBody` / `textBody`, include the matching key in **`variables`** as well.


      ### Platform billing notification templates (separate helpers, e.g. subscription / trial / payment failed)


      Typical keys include: `{{customerName}}`, `{{planName}}`, `{{currency}}`, `{{amount}}`, `{{billingCycle}}`,
      `{{nextBillingDate}}`, `{{endDate}}`, `{{dueDate}}`, `{{updatePaymentUrl}}`, `{{daysLeft}}`, `{{monthlyAmount}}`,
      `{{yearlyAmount}}`, `{{savings}}`, `{{subscribeUrl}}`.


      ### Master list (every documented token, `{{name}}` form)


      Alphabetical (case-sensitive token names as used in templates):


      `{{amount}}`, `{{appName}}`, `{{appNameDisplay}}`, `{{billingCycle}}`, `{{BRAND_INITIAL}}`, `{{BRAND_NAME}}`,
      `{{collectedAmount}}`, `{{content}}`, `{{CTA_URL}}`, `{{currency}}`, `{{customerName}}`, `{{cutOffNote}}`,
      `{{daysLeft}}`, `{{dueDate}}`, `{{endDate}}`, `{{errorMessage}}`, `{{EXPIRY_MINUTES}}`, `{{expiresIn}}`,
      `{{footerLine}}`, `{{hardLimit}}`, `{{HEADER_LOGO}}`, `{{invitationUrl}}`, `{{inviterName}}`, `{{JOIN_DATE}}`,
      `{{limit}}`, `{{LOGO_URL}}`, `{{magicLinkUrl}}`, `{{monthlyAmount}}`, `{{nextBillingDate}}`, `{{orgName}}`,
      `{{otpCode}}`, `{{paymentLink}}`, `{{percent}}`, `{{period}}`, `{{PLAN_NAME}}`, `{{planName}}`,
      `{{PLATFORM_NAME}}`, `{{PLATFORM_URL}}`, `{{POWERED_BY_PLATFORM}}`, `{{primaryColor}}`, `{{projectId}}`,
      `{{projectName}}`, `{{REQUEST_IP}}`, `{{REQUEST_TIME}}`, `{{resetUrl}}`, `{{resource}}`, `{{role}}`,
      `{{SECURITY_URL}}`, `{{senderLine}}`, `{{savings}}`, `{{softLimit}}`, `{{subscribeUrl}}`, `{{threshold}}`,
      `{{updatePaymentUrl}}`, `{{used}}`, `{{USER_EMAIL}}`, `{{USER_NAME}}`, `{{userName}}`, `{{verificationUrl}}`,
      `{{YEAR}}`, `{{yearlyAmount}}`.


      Custom templates may introduce other names; anything you type as `{{token}}` must be listed in **`variables`** and
      supplied (or defaulted) via **`data`** / layout.


      Use **GET** `/api/projects/{projectId}/email/templates` and **GET**
      `/api/projects/{projectId}/email/templates/{name}` to see which names exist and whether the project uses a
      **custom** override (`isCustomized` / `isProjectOverride`).
  - name: Usage
    description: >
      Analytics and usage monitoring. GET /api/usage/projects/{projectId}/summary returns dashboard KPIs (requests
      trend, active users, 14d volume, per-project openapi-docs latency and org-wide uptime). GET /api/usage/overage
      returns overage line items for the org's current billing period (auth required).
  - name: Search
    description: Full-text search capabilities
  - name: Billing
    description: >
      Billing and subscription management. **Fiat only** on the live API: platform subscriptions + org payment
      processing. Per-transaction processing fees are computed per payout rail and returned by
      GET /api/orgs/{orgId}/payment-processing/fee-breakdown. No crypto payment fields in billing responses.

      **Customer subscription payment flow (project-level plans):**

      1. GET /api/billing/public/projects/{projectId}/plans — list plans (no auth). Response: { plans: [...] }.

      2. POST /api/billing/public/projects/{projectId}/checkout — create checkout (no auth). Body: planId, billingCycle,
      customerInfo (email, name?), successUrl?, cancelUrl?. Response: { success, data: { checkoutUrl, authorizationUrl,
      accessCode?, reference, amount, currency } }.

      3. After user pays, POST /api/billing/public/projects/{projectId}/verify-payment?reference={reference} — verify
      and create subscription (reference is mudbase_...). Response: { success, message, data: { subscription } }.

      **Org-level BaaS plan payment (Starter, Growth, Scale — paymentService.js PLANS):**

      1. GET /api/billing/plans — list tiers (no auth). Response: { plans: [{ id, name, price, priceYearly, limits,
      overages }, ...] }.

      2. POST /api/billing/org/checkout — create a payment link (auth required). Body: planName (basic|starter|growth|scale),
      billingCycle (monthly|yearly), redirectUrl?. Response: { success, data: { link, txRef, amount, amountCents } }.

      3. After user pays, POST /api/billing/org/verify-payment?tx_ref={txRef} — verify and update org plan. Response: {
      success, message, data: { plan, billingCycle, orgId } }.

      GET /api/billing/estimate returns current-month overage estimate and forecast; GET /api/usage/overage returns
      overage line items for the current period.
  - name: Chat
    description: Real-time chat and messaging
  - name: Integrations
    description: Third-party service integrations
  - name: Project Fees
    description: ~~Project fee settings and payout management~~ (deprecated for non-custodial/project-only setup)
  - name: Roles
    description: ~~Custom role and permission management for multi-role applications~~ (deprecated for project-based setup)
  - name: Multi-Role Feature
    description: >-
      Project app roles (starter `customer` role) with per-collection CRUD; add roles via API and match signup paths to
      each role's `signupEndpoint`
  - name: Role Elevation
    description: Configurable role elevation with admin approval support
  - name: Verified Role Upgrade
    description: Secure role upgrades with payment verification
  - name: Backups
    description: Database backup and restore operations
  - name: Compliance
    description: Compliance automation and security event logging (GDPR, SOC 2)
  - name: Real-time Analytics
    description: Real-time analytics and monitoring endpoints
  - name: WebSocket Events
    description: Real-time WebSocket events for live data synchronization, chat, and notifications
  - name: Health
    description: System health and status
  - name: Monitoring
    description: Block scanner metrics, logs, analytics, errors, performance, and alerts
  - name: Add-ons
    description: Paid add-on marketplace — catalog discovery and project-scoped invocation
paths:
  /api/auth/local/register:
    post:
      tags:
        - Authentication
      summary: Register new user (project-based)
      operationId: registerLocalUser
      description: >
        When the project has **requireEmailVerification** enabled (default), the response is 201 with
        **requireVerification: true** and **no token**; the user must verify their email then sign in via login. When
        email verification is disabled, a token and refreshToken are returned.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - email
                - password
                - firstName
                - lastName
                - projectId
              properties:
                email:
                  type: string
                  format: email
                password:
                  type: string
                  minLength: 8
                firstName:
                  type: string
                lastName:
                  type: string
                projectId:
                  type: string
                agreedToTerms:
                  type: boolean
                  description: |
                    Optional. End users signing up inside a customer's app have never
                    seen or agreed to Mudbase's own Terms of Service, so this field is not
                    required here and is never recorded as platform ToS acceptance. A
                    generated-app form may send it if the app has its own ToS checkbox, but
                    Mudbase does not write it to any consent record.
            examples:
              standard:
                summary: Typical request
                value:
                  email: sarah.chen@example.com
                  password: SecurePass123!
                  firstName: Sarah
                  lastName: Chen
                  projectId: 65f1a2b3c4d5e6f7a8b9c0d1
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  email: user@example.com
                  password: password_example
                  firstName: firstName_example
                  lastName: lastName_example
                  projectId: projectId_example
      responses:
        '201':
          description: >
            When project.requireEmailVerification is on (default): no token returned; use requireVerification and
            message to prompt email verification, then user signs in via login. When off: token and refreshToken
            returned.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  requireVerification:
                    type: boolean
                    description: true when email verification is required; no token in response
                  token:
                    type: string
                    description: Present only when requireEmailVerification is false
                  refreshToken:
                    type: string
                    description: Present only when requireEmailVerification is false
                  expiresIn:
                    type: integer
                    description: Present only when token is returned
                  user:
                    type: object
                    properties:
                      id:
                        type: string
                      email:
                        type: string
                      firstName:
                        type: string
                      lastName:
                        type: string
                      emailVerified:
                        type: boolean
                      customRole:
                        type: string
              examples:
                verificationRequired:
                  summary: Email verification required (default)
                  value:
                    message: Please verify your email to sign in. Check your inbox for the verification link.
                    requireVerification: true
                    user:
                      id: 685acbe0e129932fbb7a0fc2
                      email: john.doe@mudbase.dev
                      firstName: John
                      lastName: Doe
                      emailVerified: false
                      customRole: null
                tokenReturned:
                  summary: Token returned (when requireEmailVerification is false)
                  value:
                    message: Registration successful. Please check your email for verification.
                    token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
                    refreshToken: ...
                    expiresIn: 86400
                    user:
                      id: 685acbe0e129932fbb7a0fc2
                      email: john.doe@mudbase.dev
                      firstName: John
                      lastName: Doe
                      emailVerified: false
                      customRole: null
        '400':
          $ref: '#/components/responses/BadRequest'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/auth/local/login:
    post:
      tags:
        - Authentication
      summary: Login user (project-based)
      operationId: loginLocalUser
      description: >
        When the project has **requireEmailVerification** enabled and the user has not verified their email, returns 403
        with code **EMAIL_VERIFICATION_REQUIRED** (user must verify email first, then login again).
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - email
                - password
              properties:
                email:
                  type: string
                  format: email
                password:
                  type: string
                projectId:
                  type: string
            examples:
              standard:
                summary: Typical request
                value:
                  email: sarah.chen@example.com
                  password: SecurePass123!
                  projectId: 65f1a2b3c4d5e6f7a8b9c0d1
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  email: user@example.com
                  password: password_example
                  projectId: projectId_example
      responses:
        '200':
          description: Login successful
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  token:
                    type: string
                  refreshToken:
                    type: string
                  expiresIn:
                    type: integer
                    description: Access token TTL in seconds
                  user:
                    type: object
                    properties:
                      id:
                        type: string
                      email:
                        type: string
                      firstName:
                        type: string
                      lastName:
                        type: string
                      role:
                        type: string
                      emailVerified:
                        type: boolean
                      twoFactorEnabled:
                        type: boolean
              example:
                message: Login successful
                token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
                refreshToken: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
                expiresIn: 1800
                user:
                  id: 685acbe0e129932fbb7a0fc2
                  email: john.doe@mudbase.dev
                  firstName: John
                  lastName: Doe
                  role: developer
                  emailVerified: true
                  twoFactorEnabled: false
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: Email verification required (project has requireEmailVerification and user has not verified)
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                  code:
                    type: string
                  message:
                    type: string
              example:
                error: Email verification required
                code: EMAIL_VERIFICATION_REQUIRED
                message: Please verify your email to sign in. Check your inbox for the verification link.
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/auth/local/logout:
    post:
      tags:
        - Authentication
      summary: Logout user (project-based)
      operationId: logoutLocalUser
      description: >
        Logout the current authenticated user session (project-based).

        Requires JWT Bearer token authentication. Both OrgBearerAuth and ProjectBearerAuth are supported (they use the
        same JWT token format). API keys are not supported for this endpoint.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      responses:
        '200':
          description: Logout successful
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageResponse'
              example:
                message: Logout successful
  /api/auth/local/session:
    get:
      tags:
        - Authentication
      summary: Get current session (project-based)
      operationId: getLocalSession
      description: >
        Get the current authenticated user session (project-based).

        Requires JWT Bearer token authentication. Both OrgBearerAuth and ProjectBearerAuth are supported (they use the
        same JWT token format). API keys are not supported for this endpoint.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: query
          schema:
            type: string
      responses:
        '200':
          description: Current session
          content:
            application/json:
              schema:
                type: object
                properties:
                  user:
                    type: object
                  authenticated:
                    type: boolean
              example:
                user:
                  id: 685acbe0e129932fbb7a0fc2
                  email: john.doe@mudbase.dev
                  firstName: John
                  lastName: Doe
                  project:
                    id: 65f1a2b3c4d5e6f7a8b9c0d1
                    name: Mudbase Platform
                    role: developer
                authenticated: true
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/auth/accept-invite:
    post:
      tags:
        - Authentication
      summary: Accept organization invitation
      operationId: acceptInvite
      description: |
        Accept an organization invitation using the token from the invite email link (e.g. `/invite/{token}?orgId=...`).
        Creates a new user with the invited email and adds them to the organization with the invited role.
        Returns a JWT and user so the client can log the user in immediately. No authentication required.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - token
                - password
                - firstName
                - lastName
              properties:
                token:
                  type: string
                  description: Invitation token from the invite email link
                password:
                  type: string
                  minLength: 8
                  description: Password for the new account
                firstName:
                  type: string
                lastName:
                  type: string
            examples:
              standard:
                summary: Typical request
                value:
                  token: a1b2c3d4e5f6...
                  password: SecurePass123!
                  firstName: Jane
                  lastName: Doe
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  token: verification-token-from-email-link
                  password: password_example
                  firstName: firstName_example
                  lastName: lastName_example
      responses:
        '201':
          description: Invitation accepted; user created and added to organization
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  token:
                    type: string
                    description: JWT for the new user session
                  user:
                    type: object
                    properties:
                      id:
                        type: string
                      email:
                        type: string
                      firstName:
                        type: string
                      lastName:
                        type: string
                      org:
                        type: string
                      role:
                        type: string
                      emailVerified:
                        type: boolean
              example:
                message: Invitation accepted. You are now a member of the organization.
                token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
                user:
                  id: 685acbe0e129932fbb7a0fc2
                  email: jane.doe@example.com
                  firstName: Jane
                  lastName: Doe
                  org: 65f1a2b3c4d5e6f7a8b9c0d1
                  role: developer
                  emailVerified: true
        '400':
          description: Invalid or expired token, or user already exists with this email
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
              examples:
                invalidToken:
                  value:
                    error: Invalid or expired invitation token
                expired:
                  value:
                    error: Invitation has expired
                userExists:
                  value:
                    error: User already exists with this email
        '404':
          description: Organization not found
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/auth/local/password-reset:
    post:
      tags:
        - Authentication
      summary: Request password reset (project-based, OTP)
      operationId: requestLocalPasswordReset
      description: |
        When projectId is provided, sends a 6-digit OTP to the user's email (project-based reset uses OTP, not link).
        When projectId is omitted, sends a token link (org/platform local account). Rate limited.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - email
              properties:
                email:
                  type: string
                  format: email
                  example: user@example.com
                projectId:
                  type: string
                  description: Required for project-based reset (sends OTP). Omit for org token link.
                  example: 65f1a2b3c4d5e6f7a8b9c0d1
            examples:
              standard:
                summary: Typical request
                value:
                  email: user@example.com
                  projectId: 65f1a2b3c4d5e6f7a8b9c0d1
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  email: user@example.com
                  projectId: 65f1a2b3c4d5e6f7a8b9c0d1
      responses:
        '200':
          description: OTP or reset email sent (generic message to prevent enumeration)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageResponse'
              example:
                message: If an account exists, a verification code has been sent to your email
        '400':
          $ref: '#/components/responses/BadRequest'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          description: Too many requests (rate limit)
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/auth/local/password-reset/confirm:
    post:
      tags:
        - Authentication
      summary: Confirm password reset with OTP (project-based)
      operationId: confirmLocalPasswordResetWithOtp
      description: |
        Set new password using the OTP sent to the user's email. Call after
        POST /api/auth/local/password-reset with projectId. Rate limited (OTP limit).
        If the user's email was not yet verified, it is marked as verified upon successful reset.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - email
                - projectId
                - otp
                - newPassword
              properties:
                email:
                  type: string
                  format: email
                  example: user@example.com
                projectId:
                  type: string
                  example: 65f1a2b3c4d5e6f7a8b9c0d1
                otp:
                  type: string
                  minLength: 6
                  maxLength: 6
                  pattern: ^[0-9]+$
                  example: '123456'
                newPassword:
                  type: string
                  minLength: 8
                  example: NewSecurePass123!
            examples:
              standard:
                summary: Typical request
                value:
                  email: user@example.com
                  projectId: 65f1a2b3c4d5e6f7a8b9c0d1
                  otp: '123456'
                  newPassword: NewSecurePass123!
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  email: user@example.com
                  projectId: 65f1a2b3c4d5e6f7a8b9c0d1
                  otp: '123456'
                  newPassword: NewSecurePass123!
      responses:
        '200':
          description: Password reset successful
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageResponse'
              example:
                message: Password reset successful
        '400':
          description: Invalid or expired OTP, or validation error
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          description: Too many attempts (rate limit)
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/auth/local/password-reset/{token}:
    post:
      tags:
        - Authentication
      summary: Reset password with token (project-based, legacy)
      operationId: resetLocalPassword
      description: |
        Legacy token-based completion. Prefer OTP flow: use POST .../password-reset/confirm
        with the OTP sent to email for project-based resets.
      security: []
      parameters:
        - name: token
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - password
              properties:
                password:
                  type: string
                  minLength: 8
                  example: NewSecurePass123!
                projectId:
                  type: string
                  example: 65f1a2b3c4d5e6f7a8b9c0d1
            examples:
              standard:
                summary: Typical request
                value:
                  password: NewSecurePass123!
                  projectId: 65f1a2b3c4d5e6f7a8b9c0d1
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  password: NewSecurePass123!
                  projectId: 65f1a2b3c4d5e6f7a8b9c0d1
      responses:
        '200':
          description: Password reset successful
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageResponse'
              example:
                message: Password reset successful
        '400':
          $ref: '#/components/responses/BadRequest'
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/auth/oauth/{provider}/{projectId}:
    get:
      tags:
        - Authentication
      summary: Initiate OAuth authentication
      security: []
      description: >
        Initiates OAuth authentication flow for a specified provider and project.

        The OAuth provider must be configured and enabled for the project first.

        Returns an HTTP 302 redirect to the OAuth provider's consent screen.

        Note: Swagger "Try it out" may show "Failed to fetch" for this endpoint due to browser CORS restrictions on
        cross-origin redirects. Use top-level browser navigation or curl to test.
      operationId: initiateOAuth
      parameters:
        - name: provider
          in: path
          required: true
          schema:
            type: string
            enum:
              - google
              - github
              - facebook
              - microsoft
              - apple
              - twitter
              - discord
              - linkedin
              - dropbox
              - slack
              - reddit
              - twitch
              - figma
              - zoom
              - bitbucket
              - salesforce
              - shopify
              - line
              - spotify
              - strava
              - paypal
              - asana
              - trello
              - okta
              - gitea
              - yandex
              - yahoo
              - vk
              - meetup
          example: google
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            example: 65f1a2b3c4d5e6f7a8b9c0d1
        - name: redirect_url
          in: query
          schema:
            type: string
            format: uri
          description: The URL to redirect to after authentication. Must be pre-registered in project settings.
          example: https://client.app/auth/callback
      responses:
        '302':
          description: Redirect to OAuth provider's consent screen
          headers:
            Location:
              schema:
                type: string
                format: uri
              description: OAuth provider authorization URL
        '400':
          description: OAuth provider not configured, not enabled, or missing required server/provider credentials
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                    example: google authentication not enabled for this project
              example:
                error: google authentication not enabled for this project
        '404':
          description: Project not found
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                    example: Project not found
              example:
                error: Project not found
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/auth/oauth/callback/{provider}:
    get:
      tags:
        - Authentication
      summary: OAuth callback handler (project-based)
      operationId: oauthCallback
      security: []
      description: |
        Handles OAuth callback for project-based authentication.
        This route must be matched before /api/auth/oauth/{provider}/{projectId}.
        Redirects to frontend with query params token, refreshToken, and expiresIn.
      parameters:
        - name: provider
          in: path
          required: true
          schema:
            type: string
      responses:
        '302':
          description: Redirect with token, refreshToken, and expiresIn
          headers:
            Location:
              schema:
                type: string
              description: URL with token, refreshToken, expiresIn query params
              example: https://client.app/callback?token=...&refreshToken=...&expiresIn=1800
        '400':
          $ref: '#/components/responses/BadRequest'
        '429':
          $ref: '#/components/responses/TooManyRequests'
  /api/auth/oauth/providers/available:
    get:
      tags:
        - Authentication
      summary: Get all available OAuth providers
      security: []
      description: Returns a list of all supported OAuth providers with their configuration details
      operationId: getAvailableOAuthProviders
      responses:
        '200':
          description: List of available OAuth providers
          content:
            application/json:
              schema:
                type: object
                properties:
                  providers:
                    type: array
                    items:
                      type: object
                      properties:
                        name:
                          type: string
                          example: google
                        displayName:
                          type: string
                          example: Google
                        strategy:
                          type: string
                          example: google
                        defaultScope:
                          type: array
                          items:
                            type: string
                          example:
                            - profile
                            - email
                        callbackUrl:
                          type: string
                          example: /api/auth/oauth/callback/google
                        requiredFields:
                          type: array
                          items:
                            type: string
                          example:
                            - clientId
                            - clientSecret
                  total:
                    type: integer
                    example: 29
              example:
                providers:
                  - name: google
                    displayName: Google
                    strategy: google
                    defaultScope:
                      - profile
                      - email
                    callbackUrl: /api/auth/oauth/callback/google
                    requiredFields:
                      - clientId
                      - clientSecret
                  - name: github
                    displayName: GitHub
                    strategy: github
                    defaultScope:
                      - user:email
                    callbackUrl: /api/auth/oauth/callback/github
                    requiredFields:
                      - clientId
                      - clientSecret
                total: 29
  /api/auth/magic-link/send:
    post:
      tags:
        - Authentication
      summary: Send magic link
      operationId: sendMagicLink
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/MagicLinkRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  email: user@example.com
                  projectId: 65f1a2b3c4d5e6f7a8b9c0d1
                  redirectUrl: https://app.example.com/auth/callback
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  email: user@example.com
                  projectId: projectId_example
                  redirectUrl: redirectUrl_example
      responses:
        '200':
          description: Magic link sent
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageResponse'
              example:
                message: Magic link sent successfully
  /api/auth/magic-link/verify:
    post:
      tags:
        - Authentication
      summary: Verify magic link
      operationId: verifyMagicLink
      description: |
        Verifies a magic-link token and returns a JWT for the associated user.
        The request body is `{token}` only. The project context is carried by the stored token
        data (set when the magic link was sent), not passed in the request.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - token
              properties:
                token:
                  type: string
                  example: >-
                    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InVzZXJAZXhhbXBsZS5jb20iLCJwcm9qZWN0SWQiOiI2ODVhZDMwYmUxMjk5MzJmYmI3YTEwNDciLCJpYXQiOjE3NTA3ODA4OTgsImV4cCI6MTc1MDc4NDQ5OH0.example
            examples:
              standard:
                summary: Typical request
                value:
                  token: >-
                    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InVzZXJAZXhhbXBsZS5jb20iLCJwcm9qZWN0SWQiOiI2ODVhZDMwYmUxMjk5MzJmYmI3YTEwNDciLCJpYXQiOjE3NTA3ODA4OTgsImV4cCI6MTc1MDc4NDQ5OH0.example
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  token: >-
                    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InVzZXJAZXhhbXBsZS5jb20iLCJwcm9qZWN0SWQiOiI2ODVhZDMwYmUxMjk5MzJmYmI3YTEwNDciLCJpYXQiOjE3NTA3ODA4OTgsImV4cCI6MTc1MDc4NDQ5OH0.example
      responses:
        '200':
          description: Magic link verified
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AuthResponse'
              example:
                message: Magic link verified successfully
                token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
                refreshToken: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
                expiresIn: 1800
                user:
                  _id: 685acbe0e129932fbb7a0fc2
                  email: user@example.com
                  firstName: John
                  lastName: Doe
                  role: user
  /api/auth/otp/send:
    post:
      tags:
        - Authentication
      summary: Send OTP code
      operationId: sendOTP
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/OTPSendRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  email: user@example.com
                  projectId: 65f1a2b3c4d5e6f7a8b9c0d1
                  method: email
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  phone: phone_example
                  email: user@example.com
                  projectId: projectId_example
                  method: sms
      responses:
        '200':
          description: OTP sent
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageResponse'
              example:
                message: OTP code sent successfully
  /api/auth/otp/verify:
    post:
      tags:
        - Authentication
      summary: Verify OTP code
      operationId: verifyOTP
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/OTPVerifyRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  identifier: user@example.com
                  otp: '123456'
                  projectId: 65f1a2b3c4d5e6f7a8b9c0d1
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  identifier: identifier_example
                  otp: otp_example
                  projectId: projectId_example
      responses:
        '200':
          description: OTP verified
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AuthResponse'
              example:
                message: OTP verified successfully
                token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
                refreshToken: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
                expiresIn: 1800
                user:
                  _id: 685acbe0e129932fbb7a0fc2
                  email: user@example.com
                  firstName: John
                  lastName: Doe
  /api/auth/anonymous:
    post:
      tags:
        - Authentication
      summary: Create anonymous session
      operationId: createAnonymousSession
      security: []
      description: Create an anonymous user session for guest access. Users can later convert to full accounts.
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                projectId:
                  type: string
                  description: Project ID for the anonymous session
                  example: 65f1a2b3c4d5e6f7a8b9c0d1
                deviceId:
                  type: string
                  description: Optional device identifier
                  example: device-uuid-123
            examples:
              standard:
                summary: Typical request
                value:
                  projectId: 65f1a2b3c4d5e6f7a8b9c0d1
                  deviceId: device-uuid-123
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  projectId: 65f1a2b3c4d5e6f7a8b9c0d1
                  deviceId: device-uuid-123
      responses:
        '200':
          description: Anonymous session created
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Anonymous session created
                  token:
                    type: string
                    example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
                  refreshToken:
                    type: string
                    description: Refresh token for POST /api/auth/refresh
                  expiresIn:
                    type: integer
                    example: 86400
                  user:
                    type: object
                    properties:
                      id:
                        type: string
                      email:
                        type: string
                      firstName:
                        type: string
                      lastName:
                        type: string
                      role:
                        type: string
                      isAnonymous:
                        type: boolean
                        example: true
              example:
                message: Anonymous session created
                token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
                refreshToken: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
                expiresIn: 86400
                user:
                  id: 685acbe0e129932fbb7a0fc2
                  email: anonymous_abc123@anonymous.local
                  firstName: Anonymous
                  lastName: User
                  role: viewer
                  isAnonymous: true
        '400':
          $ref: '#/components/responses/BadRequest'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/auth/anonymous/convert:
    post:
      tags:
        - Authentication
      summary: Convert anonymous account to full account
      operationId: convertAnonymousAccount
      description: >
        Convert an anonymous user session to a full authenticated account. Preserves user data. Requires JWT Bearer
        token authentication. Both OrgBearerAuth and ProjectBearerAuth are supported (they use the same JWT token
        format). API keys are not supported for this endpoint.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - email
                - password
              properties:
                email:
                  type: string
                  format: email
                  example: user@example.com
                password:
                  type: string
                  format: password
                  example: SecurePassword123!
                firstName:
                  type: string
                  example: John
                lastName:
                  type: string
                  example: Doe
            examples:
              standard:
                summary: Typical request
                value:
                  email: user@example.com
                  password: SecurePassword123!
                  firstName: John
                  lastName: Doe
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  email: user@example.com
                  password: SecurePassword123!
                  firstName: John
                  lastName: Doe
      responses:
        '200':
          description: Account converted successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Account created successfully
                  token:
                    type: string
                    example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
                  refreshToken:
                    type: string
                  expiresIn:
                    type: integer
                    example: 1800
                  user:
                    $ref: '#/components/schemas/User'
              example:
                message: Account created successfully
                token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
                refreshToken: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
                expiresIn: 1800
                user:
                  _id: 685acbe0e129932fbb7a0fc2
                  email: user@example.com
                  firstName: John
                  lastName: Doe
                  role: developer
                  emailVerified: false
                  isAnonymous: false
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/users/me:
    get:
      tags:
        - Users
      summary: Get current user profile
      operationId: getCurrentUser
      description: |
        Get the current authenticated user's profile.
        Accepts JWT Bearer token (OrgBearerAuth or ProjectBearerAuth - both are the same JWT token format).
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      responses:
        '200':
          description: User profile
          content:
            application/json:
              schema:
                type: object
                properties:
                  user:
                    $ref: '#/components/schemas/User'
              example:
                user:
                  _id: 685acbe0e129932fbb7a0fc2
                  email: john.doe@mudbase.dev
                  firstName: John
                  lastName: Doe
                  role: owner
                  emailVerified: true
                  twoFactorEnabled: false
  /api/users/update:
    patch:
      tags:
        - Users
      summary: Update user profile
      operationId: updateUserProfile
      description: >
        Update the current user's profile. Requires JWT Bearer token authentication. Both OrgBearerAuth and
        ProjectBearerAuth are supported (they use the same JWT token format). API keys are not supported for this
        endpoint.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateUserRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  firstName: John
                  lastName: Doe
                  avatar: https://example.com/avatar.jpg
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  firstName: firstName_example
                  lastName: lastName_example
                  avatar: avatar_example
      responses:
        '200':
          description: Profile updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  user:
                    $ref: '#/components/schemas/User'
              example:
                message: Profile updated successfully
                user:
                  _id: 685acbe0e129932fbb7a0fc2
                  email: john.doe@mudbase.dev
                  firstName: John
                  lastName: Doe
                  avatar: https://example.com/avatar.jpg
  /api/users/password:
    patch:
      tags:
        - Users
      summary: Change password
      operationId: changePassword
      description: >
        Change the current user's password. Accepts JWT Bearer token (OrgBearerAuth or ProjectBearerAuth - both are the
        same JWT token format). API keys are not supported for this endpoint.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ChangePasswordRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  currentPassword: OldPassword123!
                  newPassword: NewSecurePass123!
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  currentPassword: currentPassword_example
                  newPassword: newPassword_example
      responses:
        '200':
          description: Password changed
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageResponse'
              example:
                message: Password changed successfully
  /api/users/2fa/setup:
    post:
      tags:
        - Users
      summary: Setup 2FA
      operationId: setup2FA
      description: >
        Setup two-factor authentication for the current user. Requires JWT Bearer token authentication. Both
        OrgBearerAuth and ProjectBearerAuth are supported (they use the same JWT token format). API keys are not
        supported for this endpoint.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      responses:
        '200':
          description: 2FA setup data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TwoFASetupResponse'
              example:
                secret: JBSWY3DPEHPK3PXP
                qrCode: >-
                  data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==
                backupCodes:
                  - '12345678'
                  - '87654321'
  /api/users/2fa/verify:
    post:
      tags:
        - Users
      summary: Verify and enable 2FA
      operationId: verify2FA
      description: >
        Verify and enable two-factor authentication for the current user. Accepts JWT Bearer token (OrgBearerAuth or
        ProjectBearerAuth - both are the same JWT token format). API keys are not supported for this endpoint.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - token
              properties:
                token:
                  type: string
                  example: '123456'
            examples:
              standard:
                summary: Typical request
                value:
                  token: '123456'
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  token: '123456'
      responses:
        '200':
          description: 2FA enabled
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageResponse'
              example:
                message: 2FA enabled successfully
  /api/users/2fa/disable:
    post:
      tags:
        - Users
      summary: Disable 2FA
      operationId: disable2FA
      description: >
        Disable two-factor authentication for the current user. Requires JWT Bearer token authentication. Both
        OrgBearerAuth and ProjectBearerAuth are supported (they use the same JWT token format). API keys are not
        supported for this endpoint.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - password
                - token
              properties:
                password:
                  type: string
                  example: SecurePass123!
                token:
                  type: string
                  example: '123456'
            examples:
              standard:
                summary: Typical request
                value:
                  password: SecurePass123!
                  token: '123456'
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  password: SecurePass123!
                  token: '123456'
      responses:
        '200':
          description: 2FA disabled
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageResponse'
              example:
                message: 2FA disabled successfully
  /api/users/verify-email:
    post:
      tags:
        - Users
      summary: Verify email address (organization and project)
      operationId: verifyEmail
      description: |
        Verifies the user's email using the token from the link sent at signup.
        Works for both organization (platform) and project-based signups; the token
        is from the verification link (e.g. verify-email?token=... for org, or
        verify-email?token=...&project=... for project).
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - token
              properties:
                token:
                  type: string
                  description: Verification token from the email link
                projectId:
                  type: string
                  description: Optional; for project signup context (redirect hint)
            examples:
              standard:
                summary: Typical request
                value:
                  token: a1b2c3d4...
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  token: verification-token-from-email-link
                  projectId: projectId_example
      responses:
        '200':
          description: Email verified
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageResponse'
              example:
                message: Email verified successfully
        '400':
          description: Invalid verification token
  /api/users/resend-verification:
    post:
      tags:
        - Users
      summary: Resend verification email
      operationId: resendVerificationEmail
      description: |
        Sends a new verification email to the authenticated user. Rate limited
        (e.g. 3 requests per 15 minutes per user). For project-scoped users the
        link includes project context.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      responses:
        '200':
          description: Verification email sent
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageResponse'
              example:
                message: Verification email sent successfully
        '400':
          description: Email already verified
        '429':
          description: Too many requests (rate limit)
  /api/users/me/export:
    get:
      tags:
        - Users
      summary: Export user data (GDPR Article 15)
      operationId: exportUserData
      description: >
        Export all user data in JSON format for GDPR data portability compliance. Accepts JWT Bearer token
        (OrgBearerAuth or ProjectBearerAuth - both are the same JWT token format). API keys are not supported for this
        endpoint.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      responses:
        '200':
          description: User data export
          content:
            application/json:
              schema:
                type: object
                properties:
                  exportedAt:
                    type: string
                    format: date-time
                  user:
                    $ref: '#/components/schemas/User'
                  projects:
                    type: array
                    items:
                      type: object
                      additionalProperties: true
                  transactions:
                    type: array
                    items:
                      type: object
                      additionalProperties: true
                  files:
                    type: array
                    items:
                      type: object
                      additionalProperties: true
                  integrations:
                    type: array
                    items:
                      type: object
                      additionalProperties: true
                  apiKeys:
                    type: array
                    items:
                      type: object
                      additionalProperties: true
              example:
                exportedAt: '2024-12-16T10:00:00Z'
                user:
                  _id: 685acbe0e129932fbb7a0fc2
                  email: user@example.com
                  firstName: John
                  lastName: Doe
                projects: []
                transactions: []
                files: []
                integrations: []
                apiKeys: []
  /api/users/me/erase:
    post:
      tags:
        - Users
      summary: Delete user data (GDPR Article 17)
      operationId: eraseUserData
      description: |
        Request account erasure (right to be forgotten). Anonymizes PII, revokes all sessions
        and API keys, and disables the account immediately (not a grace period - the effect is
        immediate and irreversible). Accepts JWT Bearer token (OrgBearerAuth or ProjectBearerAuth
        - both are the same JWT token format). API keys are not supported for this endpoint.

        Requires re-proving your current password (skipped only for OAuth-only accounts with no
        password set) and, if 2FA is enabled, a fresh TOTP code - the same step-up re-authentication
        already required by the less-destructive `PATCH /api/users/password` and
        `POST /api/users/2fa/disable`.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - confirm
              properties:
                confirm:
                  type: string
                  enum:
                    - DELETE
                  example: DELETE
                currentPassword:
                  type: string
                  description: Required unless the account has no password set (OAuth-only)
                  example: CurrentPassword123!
                totpToken:
                  type: string
                  description: Required only if the account has 2FA enabled
                  example: '123456'
            examples:
              standard:
                summary: Typical request
                value:
                  confirm: DELETE
                  currentPassword: CurrentPassword123!
              complete:
                summary: All request fields (2FA-enabled account)
                value:
                  confirm: DELETE
                  currentPassword: CurrentPassword123!
                  totpToken: '123456'
      responses:
        '200':
          description: Account erased
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  message:
                    type: string
                    example: User data anonymized and account disabled
                  data:
                    type: object
                    properties:
                      alreadyErased:
                        type: boolean
                        example: false
                      subjectId:
                        type: string
                        example: 685acbe0e129932fbb7a0fc2
                      anonymized:
                        type: boolean
                        example: true
                      sessionsRevoked:
                        type: boolean
                        example: true
              example:
                success: true
                message: User data anonymized and account disabled
                data:
                  alreadyErased: false
                  subjectId: 685acbe0e129932fbb7a0fc2
                  anonymized: true
                  sessionsRevoked: true
        '400':
          description: Missing/invalid confirm, currentPassword, or totpToken
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
        '401':
          $ref: '#/components/responses/Unauthorized'
        '409':
          description: Sole owner of one or more organizations - transfer or delete them first
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                  soleOwnedOrgs:
                    type: array
                    items:
                      type: string
  /api/users/me/oauth-providers:
    get:
      tags:
        - Users
      summary: List linked OAuth providers
      operationId: listOAuthProviders
      description: >
        Get all OAuth providers linked to the current user's account. Accepts JWT Bearer token (OrgBearerAuth or
        ProjectBearerAuth - both are the same JWT token format). API keys are not supported for this endpoint.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      responses:
        '200':
          description: List of linked OAuth providers
          content:
            application/json:
              schema:
                type: object
                properties:
                  providers:
                    type: array
                    items:
                      type: object
                      properties:
                        provider:
                          type: string
                          example: google
                        providerId:
                          type: string
                          example: google-user-id-123
                        email:
                          type: string
                          example: user@gmail.com
                        linkedAt:
                          type: string
                          format: date-time
              example:
                providers:
                  - provider: google
                    providerId: google-user-id-123
                    email: user@gmail.com
                    linkedAt: '2024-12-01T10:00:00Z'
                  - provider: github
                    providerId: github-user-id-456
                    username: johndoe
                    linkedAt: '2024-12-15T14:30:00Z'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/users/me/oauth-providers/link/{provider}:
    get:
      tags:
        - Users
      summary: Link OAuth provider to account
      operationId: linkOAuthProvider
      description: >
        Initiate OAuth flow to link a new provider to the current account. Accepts JWT Bearer token (OrgBearerAuth or
        ProjectBearerAuth - both are the same JWT token format). API keys are not supported for this endpoint.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: provider
          in: path
          required: true
          schema:
            type: string
            enum:
              - google
              - github
              - facebook
              - microsoft
              - apple
              - twitter
              - discord
              - linkedin
          example: google
        - name: projectId
          in: query
          schema:
            type: string
          example: 65f1a2b3c4d5e6f7a8b9c0d1
      responses:
        '302':
          description: Redirect to OAuth provider
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/users/me/oauth-providers/{provider}:
    delete:
      tags:
        - Users
      summary: Unlink OAuth provider
      operationId: unlinkOAuthProvider
      description: >
        Remove an OAuth provider from the current account. Cannot unlink if it's the only authentication method.
        Requires JWT Bearer token authentication. Both OrgBearerAuth and ProjectBearerAuth are supported (they use the
        same JWT token format). API keys are not supported for this endpoint.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: provider
          in: path
          required: true
          schema:
            type: string
            enum:
              - google
              - github
              - facebook
              - microsoft
              - apple
              - twitter
              - discord
              - linkedin
          example: github
      responses:
        '200':
          description: Provider unlinked successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: OAuth provider unlinked successfully
                  provider:
                    type: string
                    example: github
              example:
                message: OAuth provider unlinked successfully
                provider: github
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/users/email-change/request:
    post:
      tags:
        - Users
      summary: Request an email address change
      operationId: requestEmailChange
      description: |
        Initiate an email-address change for the authenticated end-user.

        The user must supply their current password. If the credentials are correct and the
        new address is not already taken within the same project, Mudbase:

        - Sends a 6-digit confirmation code to the **new** address (expires in 10 minutes).
        - Sends a cancel notice with a single-use abort link to the **current** address
          (valid for 25 hours).

        Only one pending change request exists per user at a time. A new request cancels
        any previous pending one.

        **Rate limit:** 3 requests per user (or IP) per hour.

        **Restriction:** accounts that authenticate exclusively through a linked provider
        (no local password) are rejected with code `NO_PASSWORD`.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - currentPassword
                - newEmail
              properties:
                currentPassword:
                  type: string
                  description: The user's current password.
                  example: MyCurrentP@ss1
                newEmail:
                  type: string
                  format: email
                  description: The new email address to change to.
                  example: new-address@example.com
            examples:
              standard:
                summary: Typical request
                value:
                  currentPassword: MyCurrentP@ss1
                  newEmail: new-address@example.com
      responses:
        '200':
          description: Code sent successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: A confirmation code has been sent to your new email address.
        '400':
          description: |
            Bad request. The `code` field indicates the specific failure:

            | Code | Meaning |
            |------|---------|
            | `WRONG_PASSWORD` | The supplied `currentPassword` is incorrect. |
            | `NO_PASSWORD` | The account has no local password (SSO or OAuth-only). |
            | `SAME_EMAIL` | The new email is the same as the current one. |
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                  code:
                    type: string
                    enum:
                      - WRONG_PASSWORD
                      - NO_PASSWORD
                      - SAME_EMAIL
        '401':
          $ref: '#/components/responses/Unauthorized'
        '409':
          description: |
            Conflict. `code: EMAIL_TAKEN` means another user in the same project already
            uses that address. Email uniqueness is scoped per project.
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                  code:
                    type: string
                    enum:
                      - EMAIL_TAKEN
        '429':
          $ref: '#/components/responses/RateLimitExceeded'
  /api/users/email-change/confirm:
    post:
      tags:
        - Users
      summary: Confirm an email address change
      operationId: confirmEmailChange
      description: |
        Complete a pending email-address change by submitting the 6-digit code that was sent
        to the new address.

        On success:
        - The user's email address is updated immediately.
        - All existing sessions (other devices or browsers) are invalidated.
        - A fresh token pair is returned for the calling session so it remains active.
        - A `user.email.changed` webhook event is fired (project-scoped users only).

        **Attempt limit:** after 5 wrong submissions the pending request is voided. The user
        must submit a new request to try again.

        **Rate limit:** 10 requests per user (or IP) per 15 minutes.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - code
              properties:
                code:
                  type: string
                  pattern: '^\d{6}$'
                  description: The 6-digit numeric confirmation code sent to the new address.
                  example: '481923'
            examples:
              standard:
                summary: Typical request
                value:
                  code: '481923'
      responses:
        '200':
          description: Email updated. Use the returned token pair immediately.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Email address updated successfully. Other sessions have been signed out.
                  token:
                    type: string
                    description: Fresh short-lived JWT. Replace your stored token with this.
                  refreshToken:
                    type: string
                    description: Fresh refresh token. Replace your stored refresh token with this.
                  expiresIn:
                    type: integer
                    description: Seconds until the new token expires.
                    example: 1800
        '400':
          description: |
            Bad request. The `code` field indicates the specific failure:

            | Code | Meaning |
            |------|---------|
            | `WRONG_CODE` | The submitted code is incorrect. Remaining attempts are noted in `error`. |
            | `MAX_ATTEMPTS` | 5 wrong submissions. The pending request is voided. |
            | `CODE_EXPIRED` | The 10-minute TTL has passed. Submit a new request. |
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                  code:
                    type: string
                    enum:
                      - WRONG_CODE
                      - MAX_ATTEMPTS
                      - CODE_EXPIRED
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          description: |
            `code: NO_PENDING_REQUEST` - no active email-change request exists for this
            user. Either none was submitted, or it was already confirmed. Note: a request
            voided by `MAX_ATTEMPTS` keeps its record with `codeAttempts >= 5` and returns
            `MAX_ATTEMPTS` (400) on subsequent confirm calls, not this code.
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                  code:
                    type: string
                    enum:
                      - NO_PENDING_REQUEST
        '409':
          description: |
            `code: EMAIL_TAKEN` - the requested address was registered by another user in
            the same project between the request and confirm steps. The pending request is
            cancelled. Submit a new request with a different address.
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                  code:
                    type: string
                    enum:
                      - EMAIL_TAKEN
        '429':
          $ref: '#/components/responses/RateLimitExceeded'
  /api/users/email-change/cancel:
    get:
      tags:
        - Users
      summary: Cancel a pending email change (abort link)
      operationId: cancelEmailChange
      description: |
        Public endpoint. No authentication required.

        Called automatically when the account owner clicks the cancel link in the notice
        email sent to their current address after a change request was submitted. The link
        embeds a single-use token that expires 25 hours after the original request.

        The response is always a plain message and never reveals account-specific details.
        If the token is invalid, expired, or already used, a generic response is returned
        without confirming account existence.
      parameters:
        - name: token
          in: query
          required: true
          schema:
            type: string
          description: The single-use cancel token embedded in the notice email link.
      responses:
        '200':
          description: |
            Always 200 for any token lookup outcome. The `message` field indicates what happened:

            - `"Your email change has been cancelled. No change was made to your account."` - request was pending and is now cancelled.
            - `"This email change request has already been cancelled."` - the token is valid but the request was already in cancelled status (idempotent).
            - `"The email change has already been confirmed and cannot be cancelled."` - the email swap completed before the cancel arrived.
            - `"This cancellation link is not valid or has already been used."` - token not found in the system.
            - `"This cancellation link has expired. The change request also expired and no change was made."` - 25-hour TTL has passed.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
        '400':
          description: Token query parameter missing from the request.
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
  /api/users/sessions/end-all:
    post:
      tags:
        - Users
      summary: Sign out all sessions
      operationId: endAllSessions
      description: |
        Revoke every active session for the authenticated end-user across all devices and
        browsers. The calling session stays alive and receives a fresh token pair.

        Any token issued before this call is rejected on the next authenticated request.

        This action writes an audit log entry but does not fire a webhook.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      responses:
        '200':
          description: All other sessions revoked. Use the returned token pair immediately.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: All other sessions have been signed out.
                  token:
                    type: string
                    description: Fresh short-lived JWT for the calling session.
                  refreshToken:
                    type: string
                    description: Fresh refresh token for the calling session.
                  expiresIn:
                    type: integer
                    example: 1800
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/users/{userId}/sessions/end-all:
    post:
      tags:
        - Users
      summary: Sign out all sessions for a user (server-side)
      operationId: endAllSessionsForUser
      description: |
        Server-side endpoint. Requires a project-scoped API key.

        Ends all sessions for the specified end-user. The user must belong to the project
        associated with the API key. Attempting to act on a user from a different project
        returns `404` without leaking account existence.

        This is a server-initiated action. No fresh token pair is returned (the caller is
        an API key, not a user session). This action writes an audit log entry.

        JWT caller tokens are not accepted. End users who want to revoke their own sessions
        should use `POST /api/users/sessions/end-all`.
      security:
        - ApiKeyAuth: []
      parameters:
        - name: userId
          in: path
          required: true
          schema:
            type: string
            pattern: '^[0-9a-fA-F]{24}$'
          description: The MongoDB ObjectId of the user whose sessions should be ended.
          example: 685acbe0e129932fbb7a0fc2
      responses:
        '200':
          description: Sessions ended.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: User sessions ended.
        '400':
          description: Invalid user ID format.
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
        '403':
          description: |
            Forbidden. Either the API key is not scoped to a project, or a user JWT was
            supplied instead of an API key.
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
        '404':
          description: User not found in this project.
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
  /api/orgs:
    get:
      tags:
        - Organizations
      summary: Get all organizations for user
      operationId: listOrganizations
      description: |
        Get all organizations the authenticated user belongs to.
        Requires: OrgBearerAuth (organization-level authentication only).
      security:
        - OrgBearerAuth: []
      responses:
        '200':
          description: List of organizations
          content:
            application/json:
              schema:
                type: object
                properties:
                  orgs:
                    type: array
                    items:
                      $ref: '#/components/schemas/Organization'
                  total:
                    type: integer
              example:
                orgs:
                  - _id: 685acbe0e129932fbb7a0fc3
                    name: Mudbase Inc
                    slug: mudbase-inc
                    description: Main organization
                    createdAt: '2024-01-15T10:00:00.000Z'
                total: 1
    post:
      tags:
        - Organizations
      summary: ~~Create new organization~~ (disabled)
      operationId: createOrganization
      deprecated: true
      description: |
        ~~Create a new organization.~~
        This endpoint is disabled and kept only for backward compatibility in documentation.
        Requires: OrgBearerAuth (organization-level authentication only).
      security:
        - OrgBearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - name
              properties:
                name:
                  type: string
                  example: Mudbase Inc
                description:
                  type: string
                  example: Main organization
                logo:
                  type: string
                  example: https://example.com/logo.png
                website:
                  type: string
                  example: https://mudbase.dev
                parentOrgId:
                  type: string
                  example: 685acbe0e129932fbb7a0fc3
            examples:
              standard:
                summary: Typical request
                value:
                  name: Mudbase Inc
                  description: Main organization
                  logo: https://example.com/logo.png
                  website: https://mudbase.dev
                  parentOrgId: 685acbe0e129932fbb7a0fc3
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  name: Mudbase Inc
                  description: Main organization
                  logo: https://example.com/logo.png
                  website: https://mudbase.dev
                  parentOrgId: 685acbe0e129932fbb7a0fc3
      responses:
        '403':
          description: Organization creation disabled
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                    example: Creating organizations via API is disabled.
                  code:
                    type: string
                    example: ORG_CREATION_DISABLED
              example:
                error: Creating organizations via API is disabled.
                code: ORG_CREATION_DISABLED
  /api/orgs/{orgId}:
    get:
      tags:
        - Organizations
      summary: Get organization details by ID
      operationId: getOrganization
      description: |
        Get organization details by ID.
        Requires: OrgBearerAuth (organization-level authentication only).
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
      responses:
        '200':
          description: Organization details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Organization'
              example:
                _id: 685acbe0e129932fbb7a0fc3
                name: Mudbase Inc
                slug: mudbase-inc
                description: Main organization
                plan: pro
                createdAt: '2024-01-15T10:00:00.000Z'
    patch:
      tags:
        - Organizations
      summary: Update organization
      operationId: updateOrganization
      description: >
        Update organization details. Requires organization-level authentication (JWT Bearer token). API keys are not
        supported for this endpoint.
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateOrganizationRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  name: Mudbase Inc Updated
                  description: Updated organization description
                  logo: https://example.com/new-logo.png
                  website: https://mudbase.dev
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  name: name_example
                  description: description_example
                  logo: https://example.com/resource
                  website: website_example
                  settings: {}
      responses:
        '200':
          description: Organization updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Organization updated successfully
                  org:
                    $ref: '#/components/schemas/Organization'
              example:
                message: Organization updated successfully
                org:
                  _id: 685acbe0e129932fbb7a0fc3
                  name: Mudbase Inc Updated
                  slug: mudbase-inc
    delete:
      tags:
        - Organizations
      summary: Delete organization
      operationId: deleteOrganization
      description: >
        Delete an organization permanently. This is a destructive operation.

        Requires JWT Bearer token authentication. Both OrgBearerAuth and ProjectBearerAuth are supported (they use the
        same JWT token format). These are organization-level operations.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
      responses:
        '200':
          description: Organization deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Organization deleted successfully
              example:
                message: Organization deleted successfully
  /api/orgs/{orgId}/projects/{projectId}/domains:
    get:
      tags:
        - Organizations
      summary: List custom domains and DNS verification hints
      operationId: listOrgCustomDomains
      description: >
        Returns allowed hostnames for **this project**, primary hostname (per project), API base URL, and per-domain DNS
        guidance.


        Each row uses **`dnsRecords`** for the Mudbase ownership TXT (purpose **`mudbase_ownership`**) and the routing
        **CNAME** target that Mudbase provisions for the hostname (else the platform default target). Once the
        ownership TXT has passed at least once, Mudbase provisions and manages the TLS certificate for the hostname
        automatically and may add further checklist rows (for example `acme_challenge`) needed to complete certificate
        issuance.

        The certificate status field mirrors the managed certificate’s state during issuance (e.g.
        `pending_validation`, `active`).


        Managed edge TLS details are present only on deployments that serve managed edge certificates.


        Requires Growth, Scale, or Enterprise plan (custom domains included in plan features).
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Domain list and hints
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrgDomainsListResponse'
        '401':
          description: Unauthorized
        '403':
          description: Forbidden
    post:
      tags:
        - Organizations
      summary: Add a custom domain
      operationId: addOrgCustomDomain
      description: >
        Creates a pending domain row; the response **`domain`** uses the compact **`OrgDomainEntryOrgConsole`** shape
        (**`dnsRecords`** includes the Mudbase ownership TXT).

        **`dnsRecords`** may include the Mudbase TXT and routing CNAME only until the Mudbase TXT succeeds and the
        managed certificate is provisioned.

        **`flyCertificateStatus`** is typically omitted until certificate provisioning runs after the first successful **`verify-dns`**.
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AddOrgDomainRequest'
            examples:
              standard:
                summary: Minimal / required fields
                value:
                  hostname: hostname_example
              complete:
                summary: All request fields
                value:
                  hostname: hostname_example
                  setPrimary: true
      responses:
        '201':
          description: Domain created; includes dnsRecords and human-readable instructions (no extra GET required).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrgAddDomainResponse'
        '400':
          description: Validation, limit, or hostname_in_use
        '429':
          description: domain_rate_limited
  /api/orgs/{orgId}/projects/{projectId}/domains/{hostname}/dns-instructions:
    get:
      tags:
        - Organizations
      summary: Get DNS TXT record instructions for one hostname
      operationId: getOrgCustomDomainDnsInstructions
      description: >
        Returns the same shape as list/add for one hostname (URL-encode `hostname` in the path), including
        **`dnsRecords`** and **`flyCertificateStatus`** when applicable.

        See **`listOrgCustomDomains`** for how managed certificate provisioning affects those fields.
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: hostname
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Domain row with DNS hints
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrgDnsInstructionsResponse'
        '401':
          description: Unauthorized
        '403':
          description: Forbidden
        '404':
          description: domain_not_found
  /api/orgs/{orgId}/projects/{projectId}/domains/primary:
    patch:
      tags:
        - Organizations
      summary: Set primary custom domain
      operationId: setOrgPrimaryDomain
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - hostname
              properties:
                hostname:
                  type: string
            examples:
              standard:
                summary: Minimal / required fields
                value:
                  hostname: hostname_example
              complete:
                summary: All request fields
                value:
                  hostname: hostname_example
      responses:
        '200':
          description: Primary updated
  /api/orgs/{orgId}/projects/{projectId}/domains/{hostname}/verify-dns:
    post:
      tags:
        - Organizations
      summary: Verify domain ownership via DNS TXT
      operationId: verifyOrgCustomDomainDns
      description: >
        Looks up TXT at `_mudbase-verify.<hostname>` for value `mudbase-domain-verification=<token>`.


        On a successful verify, Mudbase begins provisioning and managing the TLS certificate for the hostname
        automatically. Depending on the deployment, the response may include managed edge TLS details with
        domain-control validation (DCV) hints for the certificate.


        When automated certificate provisioning is in effect, a successful verify records the certificate’s DNS
        requirements and status may advance to **`cname_approved`** in the same response (no staff **`approve-cname`**
        step). Otherwise, first success from `pending`/`failed` may move to **`cname_pending_staff`** and queue platform
        review as before.


        The **200** response may include **`dnsRecords`**, certificate status, and **`routingCnameTarget`** for
        the managed certificate once its requirements are provisioned.
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: hostname
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: >-
            TXT verified. With automated certificate provisioning, often `cname_approved` once DNS requirements are
            returned; otherwise may show `cname_pending_staff` or `dns_verified`. Includes `dnsTxtHost`/`dnsTxtValue`,
            optional managed edge TLS details, optional `dnsRecords` + certificate status when provisioning
            ran after this verify.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrgVerifyCustomDomainDnsSuccessResponse'
        '400':
          description: >-
            dns_verification_failed (TXT missing or wrong); body includes dnsTxtHost, dnsTxtValue, challengeHost,
            expectedTxt
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrgVerifyCustomDomainDnsFailureResponse'
        '503':
          description: dns_lookup_error
  /api/orgs/{orgId}/projects/{projectId}/domains/{hostname}/platform-ready:
    post:
      tags:
        - Organizations
      summary: Notify platform ops that hosting or edge work is ready (email)
      operationId: orgCustomDomainPlatformReady
      description: >
        Legacy optional ping: ops are emailed automatically on first successful Mudbase TXT verify. Use this only for an
        extra nudge.

        Sends an email to ops while the domain is in platform setup (after Mudbase TXT verification through later
        pipeline states).

        Recipients default to `admin@mudhaxkservices.com` and `admin@mudbase.dev` when `CUSTOM_DOMAIN_OPS_NOTIFY_EMAILS`
        is unset; override with that env (comma/space-separated).

        Returns **503** `email_provider_not_configured` if the platform email provider is not configured.
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: hostname
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                note:
                  type: string
                  maxLength: 2000
            examples:
              standard:
                summary: Minimal / required fields
                value:
                  note: note_example
              complete:
                summary: All request fields
                value:
                  note: note_example
      responses:
        '200':
          description: Ops notified
        '400':
          description: custom_domain_invalid_state
        '401':
          description: Unauthorized
        '403':
          description: Forbidden
        '503':
          description: email_provider_not_configured — email provider not configured on the server
  /api/orgs/{orgId}/projects/{projectId}/domains/{hostname}/submit-cname:
    post:
      tags:
        - Organizations
      summary: 'Custom domain step 2 (optional): org confirms routing CNAME was added'
      operationId: orgCustomDomainSubmitCname
      description: >
        Usually unnecessary. With automated certificate provisioning, the Mudbase TXT verify may already set
        `cname_approved`. Legacy pipelines may queue `cname_pending_staff` until staff **`approve-cname`**.

        Use **`routingCnameTarget`** from **`GET .../projects/{projectId}/domains`** (the managed routing CNAME target
        when provisioned, else the platform default target).
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: hostname
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Updated domain row
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrgPatchDomainResponse'
        '400':
          description: custom_domain_invalid_state
        '401':
          description: Unauthorized
        '403':
          description: Forbidden
  /api/orgs/{orgId}/projects/{projectId}/domains/{hostname}/verify-platform-dns:
    post:
      tags:
        - Organizations
      summary: 'Custom domain step 3: verify platform DNS (manual TXT or managed certificate readiness)'
      operationId: orgCustomDomainVerifyPlatformDns
      description: >
        **Manual path:** After staff **`PATCH .../platform-dns-verification`**, the org adds the published
        TXT and calls this endpoint. The API resolves public TXT at **`platformDnsVerification.recordName`** and matches
        **`recordValue`**. On success, `status` → **`platform_dns_pending_review`** until staff **`POST .../activate`**.


        **Automated path (default):** When automated certificate provisioning is in effect, the org calls this after the
        Mudbase TXT and the certificate DNS rows are in place (status typically **`cname_approved`** from automated
        verify-dns). The API checks the managed certificate with bounded retries. On success, `status` → **`active`**
        and the org may receive the activation email, with no staff **`approve-cname`** or **`activate`** required.


        **Legacy path:** In the legacy staff pipeline, staff **`approve-cname`** may be required first; after the managed
        certificate is ready, **`status`** becomes **`active`** on auto-activation, else **`platform_dns_pending_review`**
        until staff **`activate`**.


        **`platform_dns_verification_failed`** may include **`details.flyStatus`** / **`details.flyError`** with
        provisioning error context.
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: hostname
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: >-
            Domain row updated (`OrgPatchDomainResponse.domain`). Manual TXT path typically sets
            `platform_dns_pending_review`. Automated provisioning: typically `active` when the certificate is
            ready. Legacy staff pipeline: may set `platform_dns_pending_review` unless auto-activation is
            enabled. Body may include refreshed `dnsRecords` and `flyCertificateStatus` when certificate
            provisioning ran.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrgPatchDomainResponse'
        '400':
          description: >-
            custom_domain_invalid_state, platform_dns_verification_failed (manual TXT mismatch or managed certificate
            not active yet; see response details)
        '401':
          description: Unauthorized
        '403':
          description: Forbidden
        '503':
          description: dns_lookup_error
  /api/orgs/{orgId}/projects/{projectId}/domains/{hostname}/submit-platform-dns-verification:
    post:
      tags:
        - Organizations
      deprecated: true
      summary: Deprecated — use POST .../verify-platform-dns
      operationId: orgCustomDomainSubmitPlatformDnsVerificationDeprecated
      description: >-
        Deprecated alias of **`orgCustomDomainVerifyPlatformDns`** (same behavior: manual TXT and/or automated
        certificate provisioning per deployment).
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: hostname
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Same as verify-platform-dns
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrgPatchDomainResponse'
        '400':
          description: Error
        '503':
          description: dns_lookup_error
  /api/orgs/{orgId}/projects/{projectId}/domains/{hostname}:
    patch:
      tags:
        - Organizations
      summary: Update domain status or regenerate verification token
      operationId: patchOrgCustomDomain
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: hostname
          in: path
          required: true
          schema:
            type: string
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PatchOrgDomainRequest'
            examples:
              standard:
                summary: Minimal / required fields
                value:
                  status: pending
                  regenerateToken: true
              complete:
                summary: All request fields
                value:
                  status: pending
                  regenerateToken: true
      responses:
        '200':
          description: Updated; domain object includes dnsTxtHost and dnsTxtValue
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrgPatchDomainResponse'
    delete:
      tags:
        - Organizations
      summary: Remove a custom domain
      operationId: deleteOrgCustomDomain
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: hostname
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Removed
  /internal/provision-enterprise:
    post:
      tags:
        - Organizations
      summary: Provision enterprise dedicated API/DB (internal)
      operationId: internalProvisionEnterprise
      security:
        - InternalApiKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ProvisionEnterpriseRequest'
            examples:
              standard:
                summary: Minimal / required fields
                value:
                  orgId: orgId_example
                  provisionRequestId: provisionRequestId_example
                  apiBaseUrl: apiBaseUrl_example
                  dbRef: dbRef_example
                  serverId: serverId_example
              complete:
                summary: All request fields
                value:
                  orgId: orgId_example
                  provisionRequestId: provisionRequestId_example
                  apiBaseUrl: apiBaseUrl_example
                  dbRef: dbRef_example
                  serverId: serverId_example
                  region: region_example
                  version: version_example
                  forceOverride: true
      responses:
        '200':
          description: Applied or idempotent no-op
        '403':
          description: not_enterprise_plan
        '409':
          description: provision_conflict
  /internal/custom-domain/sweep-status:
    get:
      tags:
        - Organizations
      summary: Custom domain background sweep status (internal)
      description: >-
        Returns the last automated custom-domain sweep (TXT recheck + certificate provisioning retry), job env flags,
        and deploy troubleshooting hints when the proxy reports the app is not listening on 0.0.0.0:PORT. Requires
        header `X-Internal-Api-Key` (same as other /internal routes).
      operationId: internalCustomDomainSweepStatus
      security:
        - InternalApiKey: []
      responses:
        '200':
          description: sweep payload, jobConfig, flyHttpListenTroubleshooting
        '401':
          description: Unauthorized
        '503':
          description: INTERNAL_API_KEY not configured
  /internal/domain-dns/recheck-batch:
    post:
      tags:
        - Organizations
      summary: Batch DNS re-verification for drift (internal)
      operationId: internalDomainDnsRecheckBatch
      security:
        - InternalApiKey: []
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                maxOrgs:
                  type: integer
                recheckOlderThanHours:
                  type: integer
            examples:
              standard:
                summary: Minimal / required fields
                value:
                  maxOrgs: 1
                  recheckOlderThanHours: 1
              complete:
                summary: All request fields
                value:
                  maxOrgs: 1
                  recheckOlderThanHours: 1
      responses:
        '200':
          description: Summary counts
  /internal/org/custom-domain-addon:
    post:
      tags:
        - Organizations
      summary: Enable/disable Growth/Scale custom domain add-on (internal)
      operationId: internalCustomDomainAddon
      security:
        - InternalApiKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - orgId
                - enabled
              properties:
                orgId:
                  type: string
                enabled:
                  type: boolean
            examples:
              standard:
                summary: Minimal / required fields
                value:
                  orgId: orgId_example
                  enabled: true
              complete:
                summary: All request fields
                value:
                  orgId: orgId_example
                  enabled: true
      responses:
        '200':
          description: Updated
  /api/orgs/{orgId}/members:
    get:
      tags:
        - Organizations
      summary: Get organization members
      operationId: getOrganizationMembers
      description: >
        Get all members of an organization. Requires organization-level authentication (JWT Bearer token). API keys are
        not supported for this endpoint.
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
      responses:
        '200':
          description: Organization members
          content:
            application/json:
              schema:
                type: object
                properties:
                  members:
                    type: array
                    items:
                      $ref: '#/components/schemas/User'
                  total:
                    type: integer
              example:
                members:
                  - _id: 685acbe0e129932fbb7a0fc2
                    firstName: John
                    lastName: Doe
                    email: john.doe@example.com
                    role: admin
                total: 1
  /api/orgs/{orgId}/users:
    get:
      tags:
        - Organizations
      summary: List organization users with metadata
      operationId: getOrganizationUsers
      description: >
        Get all users in the organization with metadata (email, full name, role, accountStatus, phone, lastLogin, etc.).

        Optional query `status` filters by accountStatus (pending, active, suspended). Requires organization access and
        owner or admin role.
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
        - name: status
          in: query
          description: Filter by account status (pending, active, suspended)
          schema:
            type: string
            enum:
              - pending
              - active
              - suspended
      responses:
        '200':
          description: Organization users with metadata
          content:
            application/json:
              schema:
                type: object
                properties:
                  users:
                    type: array
                    items:
                      type: object
                      properties:
                        _id:
                          type: string
                        firstName:
                          type: string
                        lastName:
                          type: string
                        email:
                          type: string
                        avatar:
                          type: string
                        emailVerified:
                          type: boolean
                        role:
                          type: string
                        customRole:
                          type: string
                        phone:
                          type: string
                        phoneVerified:
                          type: boolean
                        lastLogin:
                          type: string
                          format: date-time
                        isActive:
                          type: boolean
                        accountStatus:
                          type: string
                          enum:
                            - pending
                            - active
                            - suspended
                        isAnonymous:
                          type: boolean
                        createdAt:
                          type: string
                          format: date-time
                        project:
                          type: object
                          properties:
                            _id:
                              type: string
                            name:
                              type: string
                            slug:
                              type: string
                  total:
                    type: integer
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/orgs/{orgId}/users/{userId}/status:
    patch:
      tags:
        - Organizations
      summary: Update user account status (activate or suspend)
      operationId: updateUserAccountStatus
      description: |
        Set a user's account status to active or suspended. Used to approve pending users or suspend/activate accounts.
        Cannot change status of an organization owner. Requires owner or admin role.
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
        - name: userId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - accountStatus
              properties:
                accountStatus:
                  type: string
                  enum:
                    - active
                    - suspended
                  description: active = full access; suspended = blocked from using the app
            examples:
              standard:
                summary: Minimal / required fields
                value:
                  accountStatus: active
              complete:
                summary: All request fields
                value:
                  accountStatus: active
      responses:
        '200':
          description: User status updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  user:
                    type: object
                    properties:
                      _id:
                        type: string
                      email:
                        type: string
                      firstName:
                        type: string
                      lastName:
                        type: string
                      accountStatus:
                        type: string
                      isActive:
                        type: boolean
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/orgs/{orgId}/users/{userId}/overview:
    get:
      tags:
        - Organizations
      summary: Get user overview and data footprint
      operationId: getUserOverview
      description: |
        Get a user's profile plus footprint (files count/size, sessions, API keys, collections in project).
        Use for dashboard to see everything tied to the user. Requires owner or admin role.
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
        - name: userId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: User and footprint
          content:
            application/json:
              schema:
                type: object
                properties:
                  user:
                    type: object
                    description: User profile (metadata only)
                  footprint:
                    type: object
                    properties:
                      fileCount:
                        type: integer
                      storageUsed:
                        type: integer
                      sessionCount:
                        type: integer
                      apiKeyCount:
                        type: integer
                      collectionsInProject:
                        type: integer
                      collections:
                        type: array
                        items:
                          type: object
                          properties:
                            _id:
                              type: string
                            name:
                              type: string
                            slug:
                              type: string
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/orgs/{orgId}/projects/{projectId}/users:
    get:
      tags:
        - Organizations
      summary: List project users with metadata
      operationId: getProjectUsers
      description: >
        Get all users in a project with metadata (email, full name, role, accountStatus, etc.).

        Optional query `status` filters by accountStatus. Project must belong to the organization. Requires owner or
        admin role.
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            example: 65f1a2b3c4d5e6f7a8b9c0d1
        - name: status
          in: query
          description: Filter by account status (pending, active, suspended)
          schema:
            type: string
            enum:
              - pending
              - active
              - suspended
      responses:
        '200':
          description: Project users with metadata
          content:
            application/json:
              schema:
                type: object
                properties:
                  users:
                    type: array
                    items:
                      type: object
                      properties:
                        _id:
                          type: string
                        firstName:
                          type: string
                        lastName:
                          type: string
                        email:
                          type: string
                        avatar:
                          type: string
                        emailVerified:
                          type: boolean
                        role:
                          type: string
                        customRole:
                          type: string
                        phone:
                          type: string
                        phoneVerified:
                          type: boolean
                        lastLogin:
                          type: string
                          format: date-time
                        isActive:
                          type: boolean
                        accountStatus:
                          type: string
                          enum:
                            - pending
                            - active
                            - suspended
                        isAnonymous:
                          type: boolean
                        createdAt:
                          type: string
                          format: date-time
                        project:
                          type: object
                          properties:
                            _id:
                              type: string
                            name:
                              type: string
                            slug:
                              type: string
                  total:
                    type: integer
                  project:
                    type: object
                    properties:
                      _id:
                        type: string
                      name:
                        type: string
                      slug:
                        type: string
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/orgs/{orgId}/invite:
    post:
      tags:
        - Organizations
      summary: Invite team member to organization
      operationId: inviteTeamMember
      description: >
        Send an invitation to a user to join the organization.

        Requires JWT Bearer token authentication. Both OrgBearerAuth and ProjectBearerAuth are supported (they use the
        same JWT token format). These are organization-level operations.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/InviteMemberRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  email: newuser@example.com
                  role: member
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  email: user@example.com
                  role: admin
      responses:
        '200':
          description: Invitation sent
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Invitation sent successfully
                  email:
                    type: string
                    example: newuser@example.com
                  role:
                    type: string
                    example: member
              example:
                message: Invitation sent successfully
                email: newuser@example.com
                role: member
  /api/orgs/{orgId}/members/{userId}/role:
    patch:
      tags:
        - Organizations
      summary: Update member role
      operationId: updateMemberRole
      description: >
        Update a member's role in the organization. Requires organization-level authentication (JWT Bearer token). API
        keys are not supported for this endpoint.
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
        - name: userId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc2
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - role
              properties:
                role:
                  type: string
                  enum:
                    - owner
                    - admin
                    - member
                    - viewer
                  example: admin
            examples:
              standard:
                summary: Typical request
                value:
                  role: admin
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  role: admin
      responses:
        '200':
          description: Role updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Role updated successfully
                  user:
                    $ref: '#/components/schemas/User'
              example:
                message: Role updated successfully
                user:
                  _id: 685acbe0e129932fbb7a0fc2
                  email: user@example.com
                  role: admin
  /api/orgs/{orgId}/members/{userId}:
    delete:
      tags:
        - Organizations
      summary: Remove team member from organization
      operationId: removeTeamMember
      description: >
        Remove a user from the organization.

        Requires JWT Bearer token authentication. Both OrgBearerAuth and ProjectBearerAuth are supported (they use the
        same JWT token format). These are organization-level operations.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
        - name: userId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc2
      responses:
        '200':
          description: Member removed
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Member removed successfully
              example:
                message: Member removed successfully
  /api/orgs/{orgId}/roles:
    post:
      tags:
        - Roles
      summary: ~~Create custom role~~ (deprecated)
      deprecated: true
      operationId: createRole
      description: >
        Create a new custom role with specific permissions for your organization.

        Requires JWT Bearer token authentication. Both OrgBearerAuth and ProjectBearerAuth are supported (they use the
        same JWT token format). These are organization-level operations.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - name
              properties:
                name:
                  type: string
                  example: Support Agent
                description:
                  type: string
                  example: Customer support team member
                permissions:
                  type: array
                  description: Legacy resource-level permissions. For data CRUD, prefer `collectionPermissions` below.
                  items:
                    type: object
                    properties:
                      resource:
                        type: string
                        enum:
                          - project
                          - collection
                          - data
                          - file
                          - api_key
                          - org
                          - member
                          - role
                      actions:
                        type: array
                        items:
                          type: string
                          enum:
                            - create
                            - read
                            - update
                            - delete
                            - manage
                      conditions:
                        type: object
                hierarchy:
                  type: number
                  minimum: 0
                  maximum: 100
                  example: 40
                collectionPermissions:
                  type: object
                  description: >-
                    Per-collection CRUD map. Keys are collection slugs; value can be action array or object with actions
                    + conditions.
                  additionalProperties:
                    oneOf:
                      - $ref: '#/components/schemas/CollectionActionList'
                      - $ref: '#/components/schemas/CollectionPermissionRule'
            examples:
              standard:
                summary: Typical request
                value:
                  name: Support Agent
                  description: Customer support team member
                  hierarchy: 40
                  collectionPermissions:
                    users:
                      - create
                      - read
                      - update
                    products:
                      - read
                    orders:
                      actions:
                        - create
                        - read
                      conditions:
                        status: active
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  name: Support Agent
                  description: Customer support team member
                  permissions:
                    - resource: project
                      actions:
                        - example_item
                      conditions: {}
                  hierarchy: 40
                  collectionPermissions:
                    users:
                      - create
                      - read
                      - update
                    products:
                      - read
                    orders:
                      actions:
                        - create
                        - read
                      conditions:
                        status: active
      responses:
        '201':
          description: Role created successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Role created successfully
                  role:
                    type: object
                    properties:
                      _id:
                        type: string
                      name:
                        type: string
                      slug:
                        type: string
                      description:
                        type: string
                      permissions:
                        type: array
                        items:
                          type: object
                          properties:
                            resource:
                              type: string
                            actions:
                              type: array
                              items:
                                type: string
                            conditions:
                              type: object
                      hierarchy:
                        type: number
                      isSystem:
                        type: boolean
                      isActive:
                        type: boolean
              example:
                message: Role created successfully
                role:
                  _id: 685acbe0e129932fbb7a0fc5
                  name: Support Agent
                  slug: support_agent
                  description: Customer support team member
                  hierarchy: 40
                  isSystem: false
                  isActive: true
        '400':
          $ref: '#/components/responses/BadRequest'
        '403':
          $ref: '#/components/responses/Forbidden'
    get:
      tags:
        - Roles
      summary: ~~List all roles~~ (deprecated)
      deprecated: true
      operationId: listRoles
      description: |
        Get all custom roles for the organization.
        Requires: OrgBearerAuth (organization-level authentication only).
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
      responses:
        '200':
          description: List of roles
          content:
            application/json:
              schema:
                type: object
                properties:
                  roles:
                    type: array
                    items:
                      type: object
                  total:
                    type: integer
              example:
                roles:
                  - _id: role123
                    name: Support Agent
                    slug: support_agent
                    hierarchy: 40
                    isSystem: false
                total: 1
  /api/orgs/{orgId}/roles/{roleId}:
    get:
      tags:
        - Roles
      summary: ~~Get role details~~ (deprecated)
      deprecated: true
      operationId: getRole
      description: |
        Get details of a specific custom role.
        Requires: OrgBearerAuth (organization-level authentication only).
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
        - name: roleId
          in: path
          required: true
          schema:
            type: string
            example: role123
      responses:
        '200':
          description: Role details
          content:
            application/json:
              schema:
                type: object
                properties:
                  role:
                    type: object
              example:
                role:
                  _id: role123
                  name: Support Agent
                  slug: support_agent
                  description: Customer support team member
                  hierarchy: 40
                  isSystem: false
                  isActive: true
                  permissions:
                    - resource: data
                      actions:
                        - read
                        - update
                      conditions:
                        collection:
                          - orders
                          - customers
                  createdAt: '2025-01-15T10:00:00.000Z'
                  updatedAt: '2025-01-15T10:00:00.000Z'
        '404':
          $ref: '#/components/responses/NotFound'
    put:
      tags:
        - Roles
      summary: ~~Update role~~ (deprecated)
      deprecated: true
      operationId: updateRole
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
        - name: roleId
          in: path
          required: true
          schema:
            type: string
            example: role123
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name:
                  type: string
                  example: Support Agent
                description:
                  type: string
                  example: Customer support team member with enhanced permissions
                permissions:
                  type: array
                  items:
                    type: object
                hierarchy:
                  type: number
                  example: 45
                isActive:
                  type: boolean
                  example: true
            examples:
              standard:
                summary: Typical request
                value:
                  name: Support Agent
                  description: Customer support team member with enhanced permissions
                  hierarchy: 45
                  isActive: true
                  permissions:
                    - resource: data
                      actions:
                        - read
                        - update
                        - delete
                      conditions:
                        collection:
                          - orders
                          - customers
                          - tickets
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  name: Support Agent
                  description: Customer support team member with enhanced permissions
                  permissions: []
                  hierarchy: 45
                  isActive: true
      responses:
        '200':
          description: Role updated successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  role:
                    type: object
              example:
                message: Role updated successfully
                role:
                  _id: role123
                  name: Support Agent
                  slug: support_agent
                  description: Customer support team member with enhanced permissions
                  hierarchy: 45
                  isSystem: false
                  isActive: true
                  permissions:
                    - resource: data
                      actions:
                        - read
                        - update
                        - delete
                      conditions:
                        collection:
                          - orders
                          - customers
                          - tickets
        '403':
          description: Cannot modify system roles
        '404':
          $ref: '#/components/responses/NotFound'
    delete:
      tags:
        - Roles
      summary: ~~Delete role~~ (deprecated)
      deprecated: true
      operationId: deleteRole
      description: >
        Delete a custom role. Cannot delete system roles or roles with active users.

        Requires JWT Bearer token authentication. Both OrgBearerAuth and ProjectBearerAuth are supported (they use the
        same JWT token format). These are organization-level operations.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
        - name: roleId
          in: path
          required: true
          schema:
            type: string
            example: role123
      responses:
        '200':
          description: Role deleted successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: Role deleted successfully
        '400':
          description: Cannot delete role with active users
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
              example:
                error: Cannot delete role with active users
        '403':
          description: Cannot delete system roles
        '404':
          $ref: '#/components/responses/NotFound'
  /api/orgs/{orgId}/users/{userId}/role:
    post:
      tags:
        - Roles
      summary: ~~Assign custom role to user~~ (deprecated)
      deprecated: true
      operationId: assignRole
      description: >
        Assign a custom role to a user in the organization.

        Requires JWT Bearer token authentication. Both OrgBearerAuth and ProjectBearerAuth are supported (they use the
        same JWT token format). These are organization-level operations.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
        - name: userId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc2
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - roleSlug
              properties:
                roleSlug:
                  type: string
                  example: support_agent
            examples:
              standard:
                summary: Typical request
                value:
                  roleSlug: support_agent
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  roleSlug: support_agent
      responses:
        '200':
          description: Role assigned successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  user:
                    type: object
              example:
                message: Role assigned successfully
                user:
                  _id: 685acbe0e129932fbb7a0fc2
                  email: john.doe@mudbase.dev
                  firstName: John
                  lastName: Doe
                  role: developer
                  customRole: support_agent
        '404':
          $ref: '#/components/responses/NotFound'
    delete:
      tags:
        - Roles
      summary: ~~Remove custom role from user~~ (deprecated)
      deprecated: true
      operationId: removeRole
      description: >
        Remove a custom role from a user in the organization.

        Requires JWT Bearer token authentication. Both OrgBearerAuth and ProjectBearerAuth are supported (they use the
        same JWT token format). These are organization-level operations.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
        - name: userId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc2
      responses:
        '200':
          description: Custom role removed successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  user:
                    type: object
              example:
                message: Custom role removed successfully
                user:
                  _id: 685acbe0e129932fbb7a0fc2
                  email: john.doe@mudbase.dev
                  firstName: John
                  lastName: Doe
                  role: developer
                  customRole: null
        '404':
          $ref: '#/components/responses/NotFound'
  /api/orgs/{orgId}/roles/{roleSlug}/users:
    get:
      tags:
        - Roles
      summary: ~~Get users with specific role~~ (deprecated)
      deprecated: true
      operationId: getUsersByRole
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
        - name: roleSlug
          in: path
          required: true
          schema:
            type: string
            example: support_agent
      responses:
        '200':
          description: List of users with this role
          content:
            application/json:
              schema:
                type: object
                properties:
                  users:
                    type: array
                    items:
                      type: object
                  total:
                    type: integer
              example:
                users:
                  - _id: 685acbe0e129932fbb7a0fc2
                    email: john.doe@mudbase.dev
                    firstName: John
                    lastName: Doe
                    role: developer
                    customRole: support_agent
                  - _id: 685acbe0e129932fbb7a0fc4
                    email: jane.smith@mudbase.dev
                    firstName: Jane
                    lastName: Smith
                    role: developer
                    customRole: support_agent
                total: 2
        '404':
          $ref: '#/components/responses/NotFound'
  /api/orgs/{orgId}/users/{userId}/permissions:
    get:
      tags:
        - Roles
      summary: ~~Check user permissions~~ (deprecated)
      deprecated: true
      operationId: checkPermissions
      description: Get all permissions for a user (system + custom role combined)
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
        - name: userId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc2
      responses:
        '200':
          description: User permissions
          content:
            application/json:
              schema:
                type: object
                properties:
                  user:
                    type: object
                  permissions:
                    type: object
                    properties:
                      system:
                        type: array
                        items:
                          type: string
                      custom:
                        type: array
                        items:
                          type: string
                      combined:
                        type: array
                        items:
                          type: string
              example:
                user:
                  _id: 685acbe0e129932fbb7a0fc2
                  email: john.doe@mudbase.dev
                  firstName: John
                  lastName: Doe
                  role: developer
                  customRole: support_agent
                permissions:
                  system:
                    - project:read
                    - project:create
                    - project:update
                    - collection:*
                    - data:*
                    - file:*
                    - api_key:create
                    - api_key:read
                    - api_key:update
                  custom:
                    - data:read
                    - data:update
                  combined:
                    - project:read
                    - project:create
                    - project:update
                    - collection:*
                    - data:*
                    - file:*
                    - api_key:create
                    - api_key:read
                    - api_key:update
        '404':
          $ref: '#/components/responses/NotFound'
  /api/projects/{projectId}/role-elevation/request:
    post:
      tags:
        - Role Elevation
      summary: Request role elevation
      description: >-
        User requests to upgrade to a specific role. May require payment or admin approval based on role
        configuration.
      operationId: requestRoleElevation
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - roleSlug
              properties:
                roleSlug:
                  type: string
                  example: seller
            examples:
              standard:
                summary: Typical request
                value:
                  roleSlug: seller
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  roleSlug: seller
      responses:
        '200':
          description: Role elevation request created or auto-approved
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  requestId:
                    type: string
                  workflow:
                    type: string
                    enum:
                      - auto_approved
                      - pending_admin_approval
                      - pending_requirements
                      - manual_approval
                  status:
                    type: string
                    enum:
                      - approved
                      - pending
                  nextSteps:
                    type: array
                    items:
                      type: string
                  estimatedApprovalTime:
                    type: string
              example:
                message: Request submitted
                requestId: req_abc123
                workflow: pending_admin_approval
                status: pending
        '400':
          description: Invalid request or already has role
        '403':
          description: Cannot request role with higher hierarchy
        '404':
          description: Role not found
  /api/projects/{projectId}/role-elevation/status:
    get:
      tags:
        - Role Elevation
      summary: Get role elevation status
      description: Get status of pending role elevation requests for current user
      operationId: getRoleElevationStatus
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: roleSlug
          in: query
          schema:
            type: string
      responses:
        '200':
          description: List of role elevation requests
          content:
            application/json:
              schema:
                type: object
                properties:
                  requests:
                    type: array
                    items:
                      type: object
              example:
                requests: []
  /api/projects/{projectId}/role-elevation/documents:
    post:
      tags:
        - Role Elevation
      summary: Upload verification documents
      description: Upload verification documents for role elevation
      operationId: uploadVerificationDocuments
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - roleSlug
                - documents
              properties:
                roleSlug:
                  type: string
                documents:
                  type: array
                  items:
                    type: object
                    properties:
                      type:
                        type: string
                      url:
                        type: string
            examples:
              standard:
                summary: Typical request
                value:
                  roleSlug: seller
                  documents:
                    - type: id
                      url: https://example.com/id.pdf
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  roleSlug: roleSlug_example
                  documents:
                    - type: type_example
                      url: url_example
      responses:
        '200':
          description: Documents uploaded successfully
  /api/orgs/{orgId}/role-elevation/pending:
    get:
      tags:
        - Role Elevation
      summary: Get pending role elevation requests (admin only)
      description: Get all pending role elevation requests requiring admin approval
      operationId: getPendingRoleElevationRequests
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
        - name: status
          in: query
          schema:
            type: string
            enum:
              - pending
              - approved
              - rejected
            default: pending
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: limit
          in: query
          schema:
            type: integer
            default: 50
      responses:
        '200':
          description: List of pending requests
          content:
            application/json:
              schema:
                type: object
                properties:
                  requests:
                    type: array
                    items:
                      type: object
                  pagination:
                    type: object
              example:
                requests: []
                pagination:
                  page: 1
                  limit: 50
                  total: 0
        '403':
          description: Insufficient permissions
  /api/orgs/{orgId}/role-elevation/{requestId}/approve:
    post:
      tags:
        - Role Elevation
      summary: Approve/reject role elevation request (admin only)
      description: Admin approves or rejects a role elevation request
      operationId: approveRoleElevation
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
        - name: requestId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - approved
              properties:
                approved:
                  type: boolean
                reason:
                  type: string
                  description: Required if approved is false
            examples:
              standard:
                summary: Typical request
                value:
                  approved: true
                  reason: All requirements met
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  approved: true
                  reason: reason_example
      responses:
        '200':
          description: Request approved/rejected
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  request:
                    type: object
              example:
                message: Request approved
                request:
                  _id: req_abc
                  status: approved
        '400':
          description: Requirements not met
        '403':
          description: Insufficient permissions
        '404':
          description: Request not found
  /api/orgs/{orgId}/users/{userId}/upgrade:
    post:
      tags:
        - Verified Role Upgrade
      summary: Verified role upgrade with payment verification
      description: Upgrade user role after verifying payment. Prevents replay attacks.
      operationId: verifiedRoleUpgrade
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
        - name: userId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - targetRole
              properties:
                targetRole:
                  type: string
                  example: seller
                paymentIntentId:
                  type: string
                  description: Payment intent ID from payment provider
                verificationId:
                  type: string
                  description: Verification ID (if required)
            examples:
              standard:
                summary: Typical request
                value:
                  targetRole: seller
                  paymentIntentId: pi_abc123
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  targetRole: seller
                  paymentIntentId: paymentIntentId_example
                  verificationId: verificationId_example
      responses:
        '200':
          description: Role upgraded successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  role:
                    type: string
                  previousRole:
                    type: string
                  upgradeLog:
                    type: string
              example:
                message: Role upgraded successfully
                role: seller
                previousRole: customer
                upgradeLog: Verified via payment pi_abc123
        '403':
          description: Payment verification failed or insufficient permissions
        '404':
          description: User or role not found
  /api/projects/{projectId}/permissions-matrix:
    get:
      tags:
        - Multi-Role Feature
      summary: Get permissions matrix (collections + featurePermissions)
      operationId: getPermissionsMatrix
      description: |
        Dashboard helper: per-collection permission rows (role actions, `dataScope`, conditions) and a per-role
        `featurePermissions` snapshot used by app-role feature gates (messaging, integrations, storage, etc.).
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            example: 65f1a2b3c4d5e6f7a8b9c0d1
      responses:
        '200':
          description: Matrix payload
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      collections:
                        type: array
                        items:
                          type: object
                      roles:
                        type: array
                        items:
                          type: object
                      features:
                        type: array
                        description: Per-role featurePermissions for app JWT gates
                        items:
                          type: object
              example:
                success: true
                data:
                  collections:
                    - id: 507f1f77bcf86cd799439011
                      name: Orders
                      slug: orders
                      permissions:
                        - role: customer
                          actions:
                            - read
                            - create
                          hasConditions: false
                          dataScope: own
                          ownerField: createdBy
                      stateMachine: null
                  roles:
                    - slug: customer
                      name: Customer
                  features:
                    - slug: customer
                      featurePermissions:
                        messaging:
                          email: true
                          sms: true
                          push: false
                        integration:
                          execute: true
                          read: true
  /api/projects/{projectId}/multi-role:
    get:
      tags:
        - Multi-Role Feature
      summary: Get multi-role feature configuration
      description: Returns project app roles (default one editable `customer` starter until you add more) and settings
      operationId: getMultiRoleConfig
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            example: 65f1a2b3c4d5e6f7a8b9c0d1
      responses:
        '200':
          description: Multi-role configuration
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      isEnabled:
                        type: boolean
                      defaultRole:
                        type: string
                      settings:
                        type: object
                      roles:
                        type: array
                        items:
                          type: object
              example:
                success: true
                data:
                  isEnabled: true
                  defaultRole: customer
                  settings:
                    allowMultipleRoles: false
                    requireRoleSelection: false
                    autoAssignDefault: true
                  roles:
                    - slug: customer
                      name: Customer
                      description: >-
                        Default app user role. Edit name/slug and assign create/read/update/delete per collection after
                        you add schemas.
                      isEnabled: true
                      isCustom: true
                      signupEndpoint: customer
                      requiresApproval: false
                      requiresPayment: false
                      defaultPermissions: []
                      collectionPermissions: []
  /api/projects/{projectId}/multi-role/settings:
    patch:
      tags:
        - Multi-Role Feature
      summary: Update multi-role feature settings
      operationId: updateMultiRoleSettings
      description: >
        Update multi-role feature settings for a project: enable/disable the feature, set which app role is the default
        at signup, and tune `settings` (`allowMultipleRoles`, `requireRoleSelection`, `autoAssignDefault`).

        This endpoint does **not** edit role definitions or permissions — use `POST/PATCH .../multi-role/roles` for that
        (same shape as **Add custom role**).

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            example: 65f1a2b3c4d5e6f7a8b9c0d1
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                isEnabled:
                  type: boolean
                  example: true
                defaultRole:
                  type: string
                  example: customer
                settings:
                  type: object
                  description: Feature toggles for signup behavior (not per-role approval flags).
                  properties:
                    allowMultipleRoles:
                      type: boolean
                      description: Whether an end user may hold multiple app roles.
                    requireRoleSelection:
                      type: boolean
                      description: >-
                        If true, signup must pick a role; if false and `autoAssignDefault` is true, `defaultRole` is
                        used when omitted.
                    autoAssignDefault:
                      type: boolean
                      description: When true, assigns `defaultRole` when the client does not specify a role at signup.
                    dataOwnerField:
                      type: string
                      default: createdBy
                      description: Default document field for dataScope `own` (e.g. createdBy, userId).
            examples:
              standard:
                summary: Typical request
                value:
                  isEnabled: true
                  defaultRole: customer
                  settings:
                    allowMultipleRoles: false
                    requireRoleSelection: false
                    autoAssignDefault: true
                    dataOwnerField: createdBy
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  isEnabled: true
                  defaultRole: customer
                  settings:
                    allowMultipleRoles: true
                    requireRoleSelection: true
                    autoAssignDefault: true
                    dataOwnerField: createdBy
      responses:
        '200':
          description: Settings updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  data:
                    type: object
                    description: >-
                      Same shape as GET `/multi-role` — `isEnabled`, `defaultRole`, `settings`, and `roles` (no raw
                      MultiRoleFeature document).
              example:
                success: true
                message: Multi-role settings updated
                data:
                  isEnabled: true
                  defaultRole: customer
                  settings:
                    allowMultipleRoles: false
                    requireRoleSelection: false
                    autoAssignDefault: true
                    dataOwnerField: createdBy
                  roles:
                    - slug: customer
                      name: Customer
                      description: >-
                        Default app user role. Edit name/slug and assign create/read/update/delete per collection after
                        you add schemas.
                      isEnabled: true
                      isCustom: true
                      signupEndpoint: customer
                      requiresApproval: false
                      requiresPayment: false
                      defaultPermissions: []
                      collectionPermissions: []
  /api/projects/{projectId}/multi-role/simulate-permissions:
    post:
      tags:
        - Multi-Role Feature
      summary: Simulate app-role feature permission for a path
      operationId: simulateAppPermissions
      description: |
        Dashboard-only. Given an app role slug and either an OpenAPI `operationId` **or** HTTP method + pathname,
        returns whether the role's `featurePermissions` would allow the operation for paths that have a feature gate.
        Unmapped paths or unknown operation IDs return `allowed: true` with reason `no_feature_gate_for_path` or
        `no_feature_gate_for_operation_id`.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - role
              properties:
                role:
                  type: string
                  description: App role slug (same as `roleSlug` elsewhere)
                  example: customer
                roleSlug:
                  type: string
                  description: Alias for `role`
                operationId:
                  type: string
                  description: OpenAPI operationId (e.g. `sendEmail`, `executeIntegration`). When set, path simulation is optional.
                  example: sendEmail
                method:
                  type: string
                  example: POST
                pathname:
                  type: string
                  description: Full path e.g. `/api/messaging/projects/{id}/messaging/email`
                  example: /api/messaging/projects/65f1a2b3c4d5e6f7a8b9c0d1/messaging/email
                path:
                  type: string
                  description: Alias for `pathname`
              oneOf:
                - required:
                    - operationId
                - required:
                    - method
                    - pathname
            examples:
              byPath:
                summary: Simulate using HTTP method + full pathname
                value:
                  role: customer
                  method: POST
                  pathname: /api/messaging/projects/65f1a2b3c4d5e6f7a8b9c0d1/messaging/email
              byOperationId:
                summary: Simulate using OpenAPI operationId (matches integration/messaging operationIds in this spec)
                value:
                  role: customer
                  operationId: sendEmail
              byPathAlias:
                summary: Using `path` instead of `pathname`
                value:
                  role: viewer
                  method: GET
                  path: /api/search/projects/65f1a2b3c4d5e6f7a8b9c0d1/search
      responses:
        '200':
          description: Simulation result
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  allowed:
                    type: boolean
                  reason:
                    type: string
                    enum:
                      - allowed
                      - feature_not_allowed
                      - no_feature_gate_for_path
                      - no_feature_gate_for_operation_id
                  evaluated:
                    type: object
                    additionalProperties: true
                    properties:
                      role:
                        type: string
                      method:
                        type: string
                      pathname:
                        type: string
                      operationId:
                        type: string
                      resource:
                        type: string
                      action:
                        type: string
              examples:
                allowedByPath:
                  summary: Mapped path; role permits action
                  value:
                    success: true
                    allowed: true
                    reason: allowed
                    evaluated:
                      role: customer
                      pathname: /api/messaging/projects/65f1a2b3c4d5e6f7a8b9c0d1/messaging/email
                      method: POST
                      resource: messaging
                      action: send_email
                deniedByPermissions:
                  summary: Mapped path; featurePermissions explicitly deny
                  value:
                    success: true
                    allowed: false
                    reason: feature_not_allowed
                    evaluated:
                      role: viewer
                      pathname: /api/messaging/projects/65f1a2b3c4d5e6f7a8b9c0d1/messaging/email
                      method: POST
                      resource: messaging
                      action: send_email
                allowedByOperationId:
                  summary: Resolved via operationId (same resource/action as path-based)
                  value:
                    success: true
                    allowed: true
                    reason: allowed
                    evaluated:
                      role: customer
                      operationId: sendEmail
                      resource: messaging
                      action: send_email
                noGateForPath:
                  summary: Path not in app-role map (pass-through for app JWT)
                  value:
                    success: true
                    allowed: true
                    reason: no_feature_gate_for_path
                    evaluated:
                      role: customer
                      pathname: /api/projects/65f1a2b3c4d5e6f7a8b9c0d1/unknown-route
                      method: GET
                noGateForOperationId:
                  summary: operationId not listed in server map
                  value:
                    success: true
                    allowed: true
                    reason: no_feature_gate_for_operation_id
                    evaluated:
                      role: customer
                      operationId: registerUser
  /api/projects/{projectId}/multi-role/roles/{roleSlug}/apply-preset:
    post:
      tags:
        - Multi-Role Feature
      summary: Apply Admin / User / Viewer feature permission preset
      operationId: applyRoleFeaturePreset
      description: |
        Sets `featurePermissions` on the role from a bundled preset (`admin`, `user`, `viewer`).
        Does not change collection CRUD or `dataScope`; use collection permission APIs for those.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: roleSlug
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - preset
              properties:
                preset:
                  type: string
                  enum:
                    - admin
                    - user
                    - viewer
            examples:
              standard:
                summary: Minimal / required fields
                value:
                  preset: admin
              complete:
                summary: All request fields
                value:
                  preset: admin
      responses:
        '200':
          description: Preset applied
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  data:
                    type: object
        '400':
          $ref: '#/components/responses/BadRequest'
  /api/projects/{projectId}/multi-role/roles/{roleSlug}/toggle:
    patch:
      tags:
        - Multi-Role Feature
      summary: Toggle role on/off
      operationId: toggleRole
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            example: 65f1a2b3c4d5e6f7a8b9c0d1
        - name: roleSlug
          in: path
          required: true
          schema:
            type: string
            example: customer
          description: Role slug to toggle (e.g. starter `customer` or a role you added).
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - isEnabled
              properties:
                isEnabled:
                  type: boolean
                  example: true
            examples:
              standard:
                summary: Typical request
                value:
                  isEnabled: true
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  isEnabled: true
      responses:
        '200':
          description: Role toggled
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  data:
                    type: object
              example:
                success: true
                message: Role enabled
                data:
                  slug: customer
                  name: Customer
                  description: >-
                    Default app user role. Edit name/slug and assign create/read/update/delete per collection after you
                    add schemas.
                  isEnabled: true
                  isCustom: true
                  signupEndpoint: customer
                  requiresApproval: false
                  requiresPayment: false
                  defaultPermissions: []
                  collectionPermissions: []
  /api/projects/{projectId}/multi-role/roles/{roleSlug}:
    patch:
      tags:
        - Multi-Role Feature
      summary: Update role configuration
      operationId: updateProjectRole
      description: |
        Partial update of an app role. **`featurePermissions`** keys must match the app-role gate map
        (`services/appRoleFeatureMap.js`); schema: `components/schemas/AppRoleFeaturePermissions`.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            example: 65f1a2b3c4d5e6f7a8b9c0d1
        - name: roleSlug
          in: path
          required: true
          schema:
            type: string
            example: customer
          description: Role slug to update (e.g. starter `customer` or a role you added).
      requestBody:
        required: true
        description: >
          Same fields as **Add custom role** — send only fields you want to change.

          `defaultPermissions` / `collectionPermissions` are normalized the same way as on create.

          **`featurePermissions`:** `components/schemas/AppRoleFeaturePermissions` (aligned with
          `services/appRoleFeatureMap.js`).
        content:
          application/json:
            schema:
              type: object
              properties:
                name:
                  type: string
                  example: App user
                description:
                  type: string
                  example: End users of the app
                signupEndpoint:
                  type: string
                  example: customer
                requiresApproval:
                  type: boolean
                  example: false
                requiresPayment:
                  type: boolean
                  example: false
                defaultPermissions:
                  type: array
                  items:
                    type: object
                collectionPermissions:
                  type: object
                  description: Per-collection CRUD map (same as POST add role).
                  additionalProperties:
                    oneOf:
                      - $ref: '#/components/schemas/CollectionActionList'
                      - $ref: '#/components/schemas/CollectionPermissionRule'
                metadata:
                  type: object
                featurePermissions:
                  $ref: '#/components/schemas/AppRoleFeaturePermissions'
            examples:
              standard:
                summary: Typical request
                value:
                  name: App user
                  description: End users of the app
                  signupEndpoint: customer
                  requiresApproval: false
                  requiresPayment: false
                  collectionPermissions:
                    posts:
                      - create
                      - read
                      - update
                      - delete
                  featurePermissions:
                    messaging:
                      email: true
                      sms: false
                      push: false
                    integration:
                      read: true
                      execute: true
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  name: App user
                  description: End users of the app
                  signupEndpoint: customer
                  requiresApproval: false
                  requiresPayment: false
                  defaultPermissions: []
                  collectionPermissions:
                    posts:
                      - create
                      - read
                      - update
                      - delete
                  metadata: {}
                  featurePermissions:
                    messaging:
                      email: true
                      sms: false
                      push: false
                    integration:
                      read: true
                      execute: true
      responses:
        '200':
          description: Role updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  data:
                    type: object
              example:
                success: true
                message: Role updated
                data:
                  slug: customer
                  name: App user
                  description: End users of the app
                  isEnabled: true
                  isCustom: true
                  signupEndpoint: customer
                  requiresApproval: false
                  requiresPayment: false
                  defaultPermissions: []
                  collectionPermissions: []
                  featurePermissions:
                    messaging:
                      email: true
                      sms: false
                      push: false
                    integration:
                      read: true
                      execute: true
  /api/projects/{projectId}/multi-role/roles:
    post:
      tags:
        - Multi-Role Feature
      summary: Add custom role
      operationId: addCustomRole
      description: >
        Add a custom role to a project with specific permissions and signup endpoint.

        Optional **`featurePermissions`** must align with app JWT gates — see
        `components/schemas/AppRoleFeaturePermissions`

        and `services/appRoleFeatureMap.js`.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            example: 65f1a2b3c4d5e6f7a8b9c0d1
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - slug
                - name
                - signupEndpoint
              properties:
                slug:
                  type: string
                  example: seller
                name:
                  type: string
                  example: Seller
                description:
                  type: string
                  example: Seller role with CRUD on seller-owned collections
                signupEndpoint:
                  type: string
                  example: seller
                requiresApproval:
                  type: boolean
                  example: false
                requiresPayment:
                  type: boolean
                  example: false
                defaultPermissions:
                  type: array
                  description: Optional global/base permissions. For collection-level CRUD use `collectionPermissions`.
                  items:
                    type: object
                    properties:
                      resource:
                        type: string
                      actions:
                        type: array
                        items:
                          type: string
                collectionPermissions:
                  type: object
                  description: Per-collection CRUD map (collection slug => actions or {actions,conditions}).
                  additionalProperties:
                    oneOf:
                      - $ref: '#/components/schemas/CollectionActionList'
                      - $ref: '#/components/schemas/CollectionPermissionRule'
                metadata:
                  type: object
                featurePermissions:
                  $ref: '#/components/schemas/AppRoleFeaturePermissions'
            examples:
              fullTesting:
                summary: Full payload for testing (all optional fields + every featurePermission bucket)
                description: |
                  Copy-paste friendly body to exercise `POST .../multi-role/roles` and validate
                  `featurePermissions` against `AppRoleFeaturePermissions` / `appRoleFeatureMap.js`.
                  Toggle individual booleans to test app JWT denials (`feature_not_allowed`).
                value:
                  slug: seller
                  name: Seller
                  description: Seller role with CRUD on seller-owned collections
                  signupEndpoint: seller
                  requiresApproval: false
                  requiresPayment: false
                  metadata:
                    notes: Example role for API integration tests
                  defaultPermissions:
                    - resource: project
                      actions:
                        - read
                    - resource: data
                      actions:
                        - read
                        - create
                  collectionPermissions:
                    listings:
                      - create
                      - read
                      - update
                      - delete
                    orders:
                      actions:
                        - create
                        - read
                      conditions:
                        status: active
                  featurePermissions:
                    messaging:
                      email: true
                      sms: true
                      push: true
                      history: true
                      stats: true
                    integration:
                      read: true
                      create: true
                      update: true
                      delete: false
                      execute: true
                      test: true
                      export: true
                      read_usage: true
                    functions:
                      create: true
                      read: true
                      update: true
                      delete: false
                      execute: true
                      simulate: true
                    data:
                      create: true
                      read: true
                      update: true
                      delete: false
                    search:
                      query: true
                      suggestions: true
                      read_analytics: true
                    usage:
                      read: true
                    storage:
                      read: true
                      create: true
                      update: true
                      delete: false
                      upload: true
                    chat:
                      read: true
                      create: true
                      update: true
                      delete: false
                    realtime:
                      read_analytics: true
                      read_active_users: true
                      presence: true
                      read_throughput: true
                      read_history: true
                    roleElevation:
                      request: true
                      status: true
                      documents: true
                    webhooks:
                      config_read: true
                      config_update: true
                      test_transformation: true
      responses:
        '201':
          description: Custom role added
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  data:
                    type: object
              examples:
                fullTesting:
                  summary: Typical success body after creating the fullTesting request
                  value:
                    success: true
                    message: Custom role added
                    data:
                      slug: seller
                      name: Seller
                      description: Seller role with CRUD on seller-owned collections
                      isEnabled: true
                      isCustom: true
                      signupEndpoint: seller
                      requiresApproval: false
                      requiresPayment: false
                      defaultPermissions:
                        - resource: project
                          actions:
                            - read
                        - resource: data
                          actions:
                            - read
                            - create
                      collectionPermissions:
                        - collectionSlug: listings
                          actions:
                            - create
                            - read
                            - update
                            - delete
                        - collectionSlug: orders
                          actions:
                            - create
                            - read
                          conditions:
                            status: active
                      metadata: {}
                      featurePermissions:
                        messaging:
                          email: true
                          sms: true
                          push: true
                          history: true
                          stats: true
                        integration:
                          read: true
                          create: true
                          update: true
                          delete: false
                          execute: true
                          test: true
                          export: true
                          read_usage: true
                        functions:
                          create: true
                          read: true
                          update: true
                          delete: false
                          execute: true
                          simulate: true
                        data:
                          create: true
                          read: true
                          update: true
                          delete: false
                        search:
                          query: true
                          suggestions: true
                          read_analytics: true
                        usage:
                          read: true
                        storage:
                          read: true
                          create: true
                          update: true
                          delete: false
                          upload: true
                        chat:
                          read: true
                          create: true
                          update: true
                          delete: false
                        realtime:
                          read_analytics: true
                          read_active_users: true
                          presence: true
                          read_throughput: true
                          read_history: true
                        roleElevation:
                          request: true
                          status: true
                          documents: true
                        webhooks:
                          config_read: true
                          config_update: true
                          test_transformation: true
  /api/projects/{projectId}/multi-role/roles/{roleSlug}/collections/{collectionId}/permissions:
    patch:
      tags:
        - Multi-Role Feature
      summary: Update collection permissions for a role
      operationId: updateCollectionPermissions
      description: >
        Update collection-specific permissions for a role in a project.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            example: 65f1a2b3c4d5e6f7a8b9c0d1
        - name: roleSlug
          in: path
          required: true
          schema:
            type: string
            example: customer
          description: Role slug (e.g. starter `customer` or a role you added).
        - name: collectionId
          in: path
          required: true
          schema:
            type: string
            example: 696ba6e4f4a9422ac4be4f74
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                actions:
                  type: array
                  items:
                    type: string
                    enum:
                      - create
                      - read
                      - update
                      - delete
                  example:
                    - create
                    - read
                    - update
                    - delete
                conditions:
                  type: object
                  example:
                    status: active
                dataScope:
                  type: string
                  enum:
                    - all
                    - own
                  description: >-
                    `all` = no automatic row-owner filter. `own` = only documents where the owner field matches the
                    authenticated app user.
                ownerField:
                  type: string
                  description: >-
                    Optional override for the document field when dataScope is `own` (default `settings.dataOwnerField`,
                    usually `createdBy`).
            examples:
              standard:
                summary: Typical request
                value:
                  actions:
                    - create
                    - read
                    - update
                    - delete
                  conditions:
                    status: active
                  dataScope: own
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  actions:
                    - create
                    - read
                    - update
                    - delete
                  conditions:
                    status: active
                  dataScope: all
                  ownerField: ownerField_example
      responses:
        '200':
          description: Collection permissions updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  data:
                    type: object
              example:
                success: true
                message: Collection permissions updated
                data:
                  slug: customer
                  name: Customer
                  description: >-
                    Default app user role. Edit name/slug and assign create/read/update/delete per collection after you
                    add schemas.
                  isEnabled: true
                  isCustom: true
                  signupEndpoint: customer
                  requiresApproval: false
                  requiresPayment: false
                  defaultPermissions: []
                  collectionPermissions:
                    - collectionId: 696ba6e4f4a9422ac4be4f74
                      collectionSlug: posts
                      actions:
                        - create
                        - read
                        - update
                        - delete
                      conditions:
                        status: active
  /api/projects/{projectId}/multi-role/roles/available:
    get:
      tags:
        - Multi-Role Feature
      summary: Get available roles for signup
      operationId: getAvailableRoles
      description: >
        Get all available roles for user signup in a project.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            example: 65f1a2b3c4d5e6f7a8b9c0d1
      responses:
        '200':
          description: List of available roles
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        slug:
                          type: string
                        name:
                          type: string
                        description:
                          type: string
                        signupEndpoint:
                          type: string
                        requiresApproval:
                          type: boolean
                        requiresPayment:
                          type: boolean
              example:
                success: true
                data:
                  - slug: customer
                    name: Customer
                    description: >-
                      Default app user role. Edit name/slug and assign create/read/update/delete per collection after
                      you add schemas.
                    signupEndpoint: customer
                    requiresApproval: false
                    requiresPayment: false
  /api/auth/local/signup/{role}:
    post:
      tags:
        - Multi-Role Feature
      summary: Register user with specific role (Local Auth)
      description: >
        Public endpoint for user registration with a specific role. The path segment must match a role's
        `signupEndpoint` (default starter is `customer`; add more roles via multi-role API).

        No authentication required - this is a public signup endpoint.
      operationId: registerWithRole
      security: []
      parameters:
        - name: role
          in: path
          required: true
          description: Must match the role's `signupEndpoint` (default `customer`; other values for roles you add).
          schema:
            type: string
            example: customer
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - email
                - password
                - firstName
                - lastName
                - projectId
              properties:
                email:
                  type: string
                  format: email
                password:
                  type: string
                firstName:
                  type: string
                lastName:
                  type: string
                projectId:
                  type: string
                agreedToTerms:
                  type: boolean
                  description: |
                    Optional. End users signing up inside a customer's app have never
                    seen or agreed to Mudbase's own Terms of Service, so this field is not
                    required here and is never recorded as platform ToS acceptance. A
                    generated-app form may send it if the app has its own ToS checkbox, but
                    Mudbase does not write it to any consent record.
            examples:
              standard:
                summary: Typical request
                value:
                  email: customer@example.com
                  password: SecurePass123!
                  firstName: Jane
                  lastName: Doe
                  projectId: 65f1a2b3c4d5e6f7a8b9c0d1
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  email: user@example.com
                  password: password_example
                  firstName: firstName_example
                  lastName: lastName_example
                  projectId: projectId_example
      responses:
        '201':
          description: >-
            Registration successful. Two response shapes depending on the project's `requireEmailVerification` setting -
            see `requireVerification` to distinguish them; `token`/`refreshToken`/`expiresIn` are only present when a
            session was issued immediately.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  requireVerification:
                    type: boolean
                    description: >-
                      True when the project requires email verification before a session is issued - no token is
                      returned in that case.
                  token:
                    type: string
                    description: JWT access token. Absent when requireVerification is true.
                  refreshToken:
                    type: string
                    description: JWT refresh token. Absent when requireVerification is true.
                  expiresIn:
                    type: integer
                    description: Access token TTL in seconds. Absent when requireVerification is true.
                  user:
                    type: object
                    properties:
                      id:
                        type: string
                      email:
                        type: string
                        format: email
                      firstName:
                        type: string
                      lastName:
                        type: string
                      role:
                        type: string
                      customRole:
                        type: string
                        nullable: true
                      emailVerified:
                        type: boolean
                  role:
                    type: object
                    properties:
                      slug:
                        type: string
                      name:
                        type: string
                      description:
                        type: string
        '400':
          description: Validation failed, or a user with this email already exists for the project
        '403':
          description: Role requires approval or payment before it can be self-assigned
        '404':
          description: Role not found or not enabled
  /api/auth/oauth/signup/{role}/{provider}/{projectId}:
    get:
      tags:
        - Multi-Role Feature
      summary: OAuth signup with specific role
      description: |
        Public endpoint that initiates OAuth signup flow with a specific role assigned during registration.
        The OAuth provider must be configured and enabled for the project first.
        The role must be available for signup in the project's multi-role configuration.
        After successful OAuth authentication, the user will be created with the specified role.
        No authentication required - this is a public signup endpoint.
      operationId: oauthSignupWithRole
      security: []
      parameters:
        - name: role
          in: path
          required: true
          description: >-
            Path segment must match the role's `signupEndpoint` (default `customer`; use each role's configured
            endpoint).
          schema:
            type: string
            example: customer
        - name: provider
          in: path
          required: true
          schema:
            type: string
            enum:
              - google
              - github
              - facebook
              - microsoft
              - apple
              - twitter
              - discord
              - linkedin
              - dropbox
              - slack
              - reddit
              - twitch
              - figma
              - zoom
              - bitbucket
              - salesforce
              - shopify
              - line
              - spotify
              - strava
              - paypal
              - asana
              - trello
              - okta
              - gitea
              - yandex
              - yahoo
              - vk
              - meetup
          example: google
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            example: 65f1a2b3c4d5e6f7a8b9c0d1
        - name: redirect_url
          in: query
          schema:
            type: string
            format: uri
          description: The URL to redirect to after authentication
          example: https://client.app/auth/callback
      responses:
        '302':
          description: Redirects to OAuth provider's consent screen
          headers:
            Location:
              schema:
                type: string
                format: uri
              description: OAuth provider authorization URL
        '400':
          description: OAuth provider not configured, role not found, or validation error
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                  message:
                    type: string
              examples:
                providerNotEnabled:
                  value:
                    error: google authentication not enabled for this project
                    message: Please configure google OAuth provider in project settings first
                roleNotFound:
                  value:
                    error: Role not found
                    message: Role with endpoint 'seller' is not available for this project
        '404':
          description: Project not found
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                    example: Project not found
              example:
                error: Project not found
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/orgs/{orgId}/usage:
    get:
      tags:
        - Organizations
      summary: Get organization usage and billing
      operationId: getOrganizationUsage
      description: |
        Get usage statistics and billing information for an organization.
        Requires: OrgBearerAuth (organization-level authentication only).
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
      responses:
        '200':
          description: Usage and billing information
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/UsageResponse'
                  - type: object
                    properties:
                      suborgs:
                        type: array
                        items:
                          type: object
                          properties:
                            _id:
                              type: string
                            name:
                              type: string
                            slug:
                              type: string
                            usage:
                              $ref: '#/components/schemas/Usage'
              example:
                usage:
                  apiCalls: 15000
                  storage: 5000000
                limits:
                  apiCalls: 100000
                  storage: 10000000
                plan:
                  name: pro
                billing:
                  status: active
                suborgs: []
  /api/orgs/{orgId}/suborgs:
    get:
      tags:
        - Organizations
      summary: ~~Get sub-organizations~~ (deprecated)
      deprecated: true
      operationId: getSubOrganizations
      description: |
        Get all sub-organizations under a parent organization.
        Requires: OrgBearerAuth (organization-level authentication only).
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
      responses:
        '200':
          description: List of sub-organizations
          content:
            application/json:
              schema:
                type: object
                properties:
                  suborgs:
                    type: array
                    items:
                      $ref: '#/components/schemas/Organization'
                  total:
                    type: integer
              example:
                suborgs: []
                total: 0
  /api/orgs/{orgId}/suborgs/{suborgId}:
    patch:
      tags:
        - Organizations
      summary: ~~Update sub-organization~~ (deprecated)
      deprecated: true
      operationId: updateSubOrganization
      description: >
        Update a sub-organization's configuration.

        Requires JWT Bearer token authentication. Both OrgBearerAuth and ProjectBearerAuth are supported (they use the
        same JWT token format). These are organization-level operations.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
        - name: suborgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc4
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateOrganizationRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  name: Sub-Organization Updated
                  description: Updated sub-organization description
                  logo: https://example.com/sub-logo.png
                  website: https://sub.mudbase.dev
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  name: name_example
                  description: description_example
                  logo: https://example.com/resource
                  website: website_example
                  settings: {}
      responses:
        '200':
          description: Sub-organization updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Sub-organization updated successfully
                  org:
                    $ref: '#/components/schemas/Organization'
              example:
                message: Sub-organization updated successfully
                org:
                  _id: 685acbe0e129932fbb7a0fc4
                  name: Sub-Organization Updated
                  slug: sub-org-updated
    delete:
      tags:
        - Organizations
      summary: ~~Delete sub-organization~~ (deprecated)
      deprecated: true
      operationId: deleteSubOrganization
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
        - name: suborgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc4
      responses:
        '200':
          description: Sub-organization deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Sub-organization deleted successfully
              example:
                message: Sub-organization deleted successfully
  /api/orgs/{orgId}/suborgs/{suborgId}/invite:
    post:
      tags:
        - Organizations
      summary: ~~Invite member to sub-organization~~ (deprecated)
      deprecated: true
      operationId: inviteSubOrganizationMember
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
        - name: suborgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc4
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/InviteMemberRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  email: user@suborg.example.com
                  role: viewer
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  email: user@example.com
                  role: admin
      responses:
        '200':
          description: Invitation sent
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Invitation sent successfully
                  email:
                    type: string
                    example: user@suborg.example.com
                  role:
                    type: string
                    example: viewer
              example:
                message: Invitation sent successfully
                email: user@suborg.example.com
                role: viewer
  /api/orgs/{orgId}/suborgs/{suborgId}/members/{userId}/role:
    patch:
      tags:
        - Organizations
      summary: ~~Update sub-organization member role~~ (deprecated)
      deprecated: true
      operationId: updateSubOrganizationMemberRole
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
        - name: suborgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc4
        - name: userId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc2
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - role
              properties:
                role:
                  type: string
                  enum:
                    - owner
                    - admin
                    - member
                    - viewer
                  example: admin
            examples:
              standard:
                summary: Typical request
                value:
                  role: admin
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  role: admin
      responses:
        '200':
          description: Role updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Role updated successfully
                  user:
                    $ref: '#/components/schemas/User'
              example:
                message: Role updated successfully
                user:
                  _id: 685acbe0e129932fbb7a0fc2
                  email: user@example.com
                  role: admin
  /api/orgs/{orgId}/suborgs/{suborgId}/members/{userId}:
    delete:
      tags:
        - Organizations
      summary: ~~Remove member from sub-organization~~ (deprecated)
      deprecated: true
      operationId: removeSubOrganizationMember
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
        - name: suborgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc4
        - name: userId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc2
      responses:
        '200':
          description: Member removed
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Member removed successfully
              example:
                message: Member removed successfully
  /api/orgs/plan/{orgId}:
    patch:
      tags:
        - Organizations
      summary: Update organization plan
      operationId: updateOrganizationPlan
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
            example: 685acbe0e129932fbb7a0fc3
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - plan
              properties:
                plan:
                  type: string
                  enum:
                    - free
                    - pro
                  example: pro
            examples:
              standard:
                summary: Typical request
                value:
                  plan: pro
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  plan: pro
      responses:
        '200':
          description: Plan updated (or error if trying to upgrade to paid)
          content:
            application/json:
              schema:
                oneOf:
                  - type: object
                    properties:
                      message:
                        type: string
                        example: Organization plan updated successfully
                      org:
                        $ref: '#/components/schemas/Organization'
                  - type: object
                    properties:
                      error:
                        type: string
                        example: Plan upgrades must be done through the billing system
                      message:
                        type: string
                        example: Please use /api/billing routes to upgrade your plan
              examples:
                success:
                  summary: Plan updated successfully
                  value:
                    message: Organization plan updated successfully
                    org:
                      _id: 685acbe0e129932fbb7a0fc3
                      name: Mudbase Inc
                      slug: mudbase-inc
                billingRequired:
                  summary: Upgrade requires billing
                  value:
                    error: Plan upgrades must be done through the billing system
                    message: Please use /api/billing routes to upgrade your plan
  /api/projects/{id}/logo:
    post:
      tags:
        - Projects
      summary: Upload project logo (by project ID)
      operationId: uploadProjectLogo
      description: >
        Upload a logo image for a project. File is stored in the platform storage under **logo/project/{projectId}/**.
        The public URL is saved to the project's **logoUrl** field and used in project-related emails and UI. Project is
        resolved from the authenticated user's org. Use multipart/form-data with field name **logo**. Allowed types:
        PNG, JPEG, GIF, WebP. Max size 2MB.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Project ID
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required:
                - logo
              properties:
                logo:
                  type: string
                  format: binary
                  description: Logo image (PNG, JPEG, GIF, or WebP; max 2MB)
            examples:
              standard:
                summary: Minimal / required fields
                value:
                  logo: <binary file>
              complete:
                summary: All request fields
                value:
                  logo: <binary file>
      responses:
        '200':
          description: Logo uploaded and project logoUrl updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  logoUrl:
                    type: string
                    format: uri
                  project:
                    $ref: '#/components/schemas/Project'
        '400':
          description: No file, invalid type, or size exceeded
        '404':
          description: Project not found
        '503':
          description: Object storage not configured
  /api/projects/{orgId}/projects:
    get:
      tags:
        - Projects
      summary: List all projects
      operationId: listProjects
      description: |
        List all projects in an organization.
        Requires: OrgBearerAuth (organization-level authentication only).
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
          description: Organization ID
      responses:
        '200':
          description: Projects list
          content:
            application/json:
              schema:
                type: object
                properties:
                  projects:
                    type: array
                    items:
                      $ref: '#/components/schemas/Project'
                  total:
                    type: integer
              example:
                projects:
                  - _id: 65f1a2b3c4d5e6f7a8b9c0d1
                    name: Mudbase Platform
                    description: Main platform for Mudbase services
                    slug: mudbase-platform
                    org: 685acbe0e129932fbb7a0fc3
                    createdAt: '2024-01-15T10:00:00.000Z'
                  - _id: 685ad30be129932fbb7a1048
                    name: E-commerce API
                    description: E-commerce backend service
                    slug: ecommerce-api
                    org: 685acbe0e129932fbb7a0fc3
                    createdAt: '2024-01-16T14:30:00.000Z'
                total: 2
    post:
      tags:
        - Projects
      summary: Create new project
      operationId: createProject
      description: |
        Create a new project in an organization.
        Requires: OrgBearerAuth (organization-level authentication only).
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
          description: Organization ID
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateProjectRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  name: My New Project
                  description: A new project description
                  orgId: 685acbe0e129932fbb7a0fc3
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  name: Mudbase Platform
                  description: Main platform for Mudbase services
                  slug: mudbase-platform
                  orgId: 685acbe0e129932fbb7a0fc3
      responses:
        '201':
          description: Project created
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  project:
                    $ref: '#/components/schemas/Project'
              example:
                message: Project created successfully
                project:
                  _id: 65f1a2b3c4d5e6f7a8b9c0d1
                  name: Mudbase Platform
                  description: Main platform for Mudbase services
                  slug: mudbase-platform
                  org: 685acbe0e129932fbb7a0fc3
                  apiKey: pk_live_abc123xyz789
                  createdAt: '2024-01-15T10:00:00.000Z'
                  updatedAt: '2024-01-15T10:00:00.000Z'
  /api/projects/{orgId}/projects/{id}:
    get:
      tags:
        - Projects
      summary: Get single project
      operationId: getProject
      description: >
        Get project details by ID.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
          description: Organization ID
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Project ID
      responses:
        '200':
          description: Project details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Project'
              example:
                _id: 65f1a2b3c4d5e6f7a8b9c0d1
                name: Mudbase Platform
                description: Main platform for Mudbase services
                slug: mudbase-platform
                org: 685acbe0e129932fbb7a0fc3
                apiKey: pk_live_abc123xyz789
                createdAt: '2024-01-15T10:00:00.000Z'
                updatedAt: '2024-01-15T10:00:00.000Z'
        '404':
          $ref: '#/components/responses/NotFound'
    patch:
      tags:
        - Projects
      summary: Update project
      operationId: updateProject
      description: >
        Update project configuration (name, description, settings).

        **Settings toggles:** **requireEmailVerification** (default true) — when on, new email signups do not get a
        token until they verify; login is blocked until verified. **requirePhoneVerification** (default false) — when
        on, phone/OTP users must verify before token. **defaultUserAccountStatus** — **active** (default) or
        **pending**; when pending, new users must be approved by org owner/admin before they can perform data/storage
        operations.

        Requires JWT Bearer token authentication. Both OrgBearerAuth and ProjectBearerAuth are supported (they use the
        same JWT token format). These are organization-level operations.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
          description: Organization ID
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Project ID
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateProjectRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  name: Updated Project Name
                  description: Updated project description
                  settings:
                    requireEmailVerification: true
                    requirePhoneVerification: false
                    defaultUserAccountStatus: active
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  name: Mudbase Platform
                  description: Main platform for Mudbase services
                  logoUrl: https://example.com/resource
                  settings:
                    requireEmailVerification: true
                    requirePhoneVerification: false
                    defaultUserAccountStatus: active
                  auth: {}
      responses:
        '200':
          description: Project updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  project:
                    $ref: '#/components/schemas/Project'
              example:
                message: Project updated successfully
                project:
                  _id: 65f1a2b3c4d5e6f7a8b9c0d1
                  name: Updated Project Name
                  description: Updated project description
                  slug: updated-project
                  org: 685acbe0e129932fbb7a0fc3
                  apiKey: pk_live_abc123xyz789
                  updatedAt: '2024-01-15T11:00:00.000Z'
    delete:
      tags:
        - Projects
      summary: Delete project
      operationId: deleteProject
      description: >
        Delete a project permanently. This is a destructive operation.

        Requires JWT Bearer token authentication. Both OrgBearerAuth and ProjectBearerAuth are supported (they use the
        same JWT token format). These are organization-level operations.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
          description: Organization ID
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Project ID
      responses:
        '200':
          description: Project deleted
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageResponse'
              example:
                message: Project deleted successfully
  /api/projects/{orgId}/projects/{id}/logo:
    post:
      tags:
        - Projects
      summary: Upload project logo (by org and project ID)
      operationId: uploadProjectLogoByOrg
      description: >
        Upload a logo image for a project. File is stored in the platform storage under **logo/project/{projectId}/**.
        The public URL is saved to the project's **logoUrl** field. Use multipart/form-data with field name **logo**.
        Allowed types: PNG, JPEG, GIF, WebP. Max size 2MB. Requires project update permission and membership in the
        organization.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
          description: Organization ID
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Project ID
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required:
                - logo
              properties:
                logo:
                  type: string
                  format: binary
                  description: Logo image (PNG, JPEG, GIF, or WebP; max 2MB)
            examples:
              standard:
                summary: Minimal / required fields
                value:
                  logo: <binary file>
              complete:
                summary: All request fields
                value:
                  logo: <binary file>
      responses:
        '200':
          description: Logo uploaded and project logoUrl updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  logoUrl:
                    type: string
                    format: uri
                  project:
                    $ref: '#/components/schemas/Project'
        '400':
          description: No file, invalid type, or size exceeded
        '404':
          description: Project or organization not found
        '503':
          description: Object storage not configured
  /api/auth/oauth/projects/{projectId}/providers:
    get:
      tags:
        - Projects
      summary: Get configured OAuth providers for a project
      description: Returns a list of OAuth providers that are configured and enabled for the specified project
      operationId: getProjectOAuthProviders
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            example: 65f1a2b3c4d5e6f7a8b9c0d1
      responses:
        '200':
          description: List of configured OAuth providers
          content:
            application/json:
              schema:
                type: object
                properties:
                  providers:
                    type: array
                    items:
                      type: object
                      properties:
                        name:
                          type: string
                          example: google
                        displayName:
                          type: string
                          example: Sign in with Google
                        authUrl:
                          type: string
                          example: /api/auth/oauth/google?projectId=65f1a2b3c4d5e6f7a8b9c0d1
                  total:
                    type: integer
                    example: 3
              example:
                providers:
                  - name: google
                    displayName: Sign in with Google
                    authUrl: /api/auth/oauth/google?projectId=65f1a2b3c4d5e6f7a8b9c0d1
                  - name: github
                    displayName: Sign in with GitHub
                    authUrl: /api/auth/oauth/github?projectId=65f1a2b3c4d5e6f7a8b9c0d1
                total: 2
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/auth/oauth/projects/{projectId}/providers/{provider}:
    get:
      tags:
        - Projects
      summary: Get OAuth provider configuration
      description: Returns the configuration for a specific OAuth provider for the project (without sensitive data)
      operationId: getOAuthProviderConfig
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            example: 65f1a2b3c4d5e6f7a8b9c0d1
        - name: provider
          in: path
          required: true
          schema:
            type: string
            enum:
              - google
              - github
              - facebook
              - microsoft
              - apple
              - twitter
              - discord
              - linkedin
              - dropbox
              - slack
              - reddit
              - twitch
              - figma
              - zoom
              - bitbucket
              - salesforce
              - shopify
              - line
              - spotify
              - strava
              - paypal
              - asana
              - trello
              - okta
              - gitea
              - yandex
              - yahoo
              - vk
              - meetup
            example: google
      responses:
        '200':
          description: OAuth provider configuration
          content:
            application/json:
              schema:
                type: object
                properties:
                  name:
                    type: string
                    example: google
                  enabled:
                    type: boolean
                    example: true
                  displayName:
                    type: string
                    example: Sign in with Google
                  config:
                    type: object
                    properties:
                      clientId:
                        type: string
                        example: 123456789-abcdefghijklmnop.apps.googleusercontent.com
                      scope:
                        type: array
                        items:
                          type: string
                        example:
                          - profile
                          - email
              example:
                name: google
                enabled: true
                displayName: Sign in with Google
                config:
                  clientId: 123456789-abcdefghijklmnop.apps.googleusercontent.com
                  scope:
                    - profile
                    - email
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
    post:
      tags:
        - Projects
      summary: Configure OAuth provider for a project
      description: Creates or updates the configuration for an OAuth provider for the specified project
      operationId: configureOAuthProvider
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            example: 65f1a2b3c4d5e6f7a8b9c0d1
        - name: provider
          in: path
          required: true
          schema:
            type: string
            enum:
              - google
              - github
              - facebook
              - microsoft
              - apple
              - twitter
              - discord
              - linkedin
              - dropbox
              - slack
              - reddit
              - twitch
              - figma
              - zoom
              - bitbucket
              - salesforce
              - shopify
              - line
              - spotify
              - strava
              - paypal
              - asana
              - trello
              - okta
              - gitea
              - yandex
              - yahoo
              - vk
              - meetup
            example: google
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - enabled
                - clientId
                - clientSecret
              properties:
                enabled:
                  type: boolean
                  description: Whether the OAuth provider is enabled
                  example: true
                clientId:
                  type: string
                  description: OAuth client ID from the provider
                  example: 123456789-abcdefghijklmnop.apps.googleusercontent.com
                clientSecret:
                  type: string
                  description: OAuth client secret from the provider
                  example: GOCSPX-abcdefghijklmnopqrstuvwxyz
                scope:
                  type: array
                  description: OAuth scopes to request
                  items:
                    type: string
                  example:
                    - profile
                    - email
                displayName:
                  type: string
                  description: Custom display name for the provider
                  example: Sign in with Google
            examples:
              standard:
                summary: Typical request
                value:
                  enabled: true
                  clientId: 123456789-abcdefghijklmnop.apps.googleusercontent.com
                  clientSecret: GOCSPX-abcdefghijklmnopqrstuvwxyz
                  scope:
                    - profile
                    - email
                  displayName: Sign in with Google
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  enabled: true
                  clientId: 123456789-abcdefghijklmnop.apps.googleusercontent.com
                  clientSecret: GOCSPX-abcdefghijklmnopqrstuvwxyz
                  scope:
                    - profile
                    - email
                  displayName: Sign in with Google
      responses:
        '200':
          description: OAuth provider configured successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: google OAuth configuration updated
                  provider:
                    type: object
                    properties:
                      name:
                        type: string
                        example: google
                      enabled:
                        type: boolean
                        example: true
                      displayName:
                        type: string
                        example: Sign in with Google
              example:
                message: google OAuth configuration updated
                provider:
                  name: google
                  enabled: true
                  displayName: Sign in with Google
        '400':
          $ref: '#/components/responses/BadRequest'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '500':
          $ref: '#/components/responses/InternalServerError'
    patch:
      tags:
        - Projects
      summary: Update OAuth provider configuration
      description: Updates the configuration for an OAuth provider for the specified project
      operationId: updateOAuthProviderConfig
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            example: 65f1a2b3c4d5e6f7a8b9c0d1
        - name: provider
          in: path
          required: true
          schema:
            type: string
            enum:
              - google
              - github
              - facebook
              - microsoft
              - apple
              - twitter
              - discord
              - linkedin
              - dropbox
              - slack
              - reddit
              - twitch
              - figma
              - zoom
              - bitbucket
              - salesforce
              - shopify
              - line
              - spotify
              - strava
              - paypal
              - asana
              - trello
              - okta
              - gitea
              - yandex
              - yahoo
              - vk
              - meetup
            example: google
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                enabled:
                  type: boolean
                  description: Whether the OAuth provider is enabled
                  example: true
                clientId:
                  type: string
                  description: OAuth client ID from the provider
                  example: 123456789-abcdefghijklmnop.apps.googleusercontent.com
                clientSecret:
                  type: string
                  description: OAuth client secret from the provider
                  example: GOCSPX-abcdefghijklmnopqrstuvwxyz
                scope:
                  type: array
                  description: OAuth scopes to request
                  items:
                    type: string
                  example:
                    - profile
                    - email
                displayName:
                  type: string
                  description: Custom display name for the provider
                  example: Sign in with Google
            examples:
              standard:
                summary: Typical request
                value:
                  enabled: true
                  clientId: 123456789-abcdefghijklmnop.apps.googleusercontent.com
                  clientSecret: GOCSPX-abcdefghijklmnopqrstuvwxyz
                  scope:
                    - profile
                    - email
                  displayName: Sign in with Google
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  enabled: true
                  clientId: 123456789-abcdefghijklmnop.apps.googleusercontent.com
                  clientSecret: GOCSPX-abcdefghijklmnopqrstuvwxyz
                  scope:
                    - profile
                    - email
                  displayName: Sign in with Google
      responses:
        '200':
          description: OAuth provider configuration updated successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: google OAuth configuration updated
                  provider:
                    type: object
                    properties:
                      name:
                        type: string
                        example: google
                      enabled:
                        type: boolean
                        example: true
                      displayName:
                        type: string
                        example: Sign in with Google
              example:
                message: google OAuth configuration updated
                provider:
                  name: google
                  enabled: true
                  displayName: Sign in with Google
        '400':
          $ref: '#/components/responses/BadRequest'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/projects/{orgId}/projects/{id}/usage:
    get:
      tags:
        - Projects
      summary: Get project usage statistics
      operationId: getProjectUsage
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
          description: Organization ID
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Project ID
      responses:
        '200':
          description: Project usage statistics
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ProjectUsageResponse'
              example:
                usage:
                  apiCalls: 15000
                  storage: 52428800
                  bandwidth: 1073741824
                  databaseReads: 5000
                  databaseWrites: 2000
                limits:
                  apiCalls: 100000
                  storage: 1073741824
                  bandwidth: 10737418240
                  databaseReads: 50000
                  databaseWrites: 10000
  /api/projects/{orgId}/projects/{id}/auth/captcha:
    get:
      tags:
        - Projects
      summary: Get project CAPTCHA configuration
      description: |
        Get CAPTCHA configuration for a project. This is a public endpoint that returns the site key 
        and settings needed for frontend integration. Secret key is never returned.
      operationId: getProjectCaptchaConfig
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
          description: Organization ID
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Project ID
      responses:
        '200':
          description: CAPTCHA configuration
          content:
            application/json:
              schema:
                type: object
                properties:
                  captcha:
                    type: object
                    properties:
                      enabled:
                        type: boolean
                        description: Whether CAPTCHA is enabled for this project
                      version:
                        type: string
                        enum:
                          - v2
                          - v3
                        description: reCAPTCHA version (v2 or v3)
                      siteKey:
                        type: string
                        nullable: true
                        description: Public site key for frontend integration
                      minScore:
                        type: number
                        minimum: 0
                        maximum: 1
                        description: Minimum score threshold for reCAPTCHA v3
              example:
                captcha:
                  enabled: true
                  version: v3
                  siteKey: 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
                  minScore: 0.5
        '404':
          $ref: '#/components/responses/NotFound'
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/schemas/projects/{projectId}/collections:
    get:
      tags:
        - Collections
      summary: List collections in project
      operationId: listCollections
      description: >
        List all collections in a project.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Collections list
          content:
            application/json:
              schema:
                type: object
                properties:
                  collections:
                    type: array
                    items:
                      $ref: '#/components/schemas/Collection'
                  total:
                    type: integer
              example:
                collections:
                  - _id: 74a2b3c4d5e6f7a8b9c0d1e2
                    name: users
                    slug: users
                    project: 65f1a2b3c4d5e6f7a8b9c0d1
                    fields:
                      - name: email
                        type: email
                        required: true
                        unique: true
                      - name: firstName
                        type: string
                        required: true
                      - name: lastName
                        type: string
                        required: true
                    createdAt: '2024-01-15T10:00:00.000Z'
                  - _id: 685ada8fd9416ac02f171ac0
                    name: products
                    slug: products
                    project: 65f1a2b3c4d5e6f7a8b9c0d1
                    fields:
                      - name: name
                        type: string
                        required: true
                      - name: price
                        type: number
                        required: true
                    createdAt: '2024-01-15T11:00:00.000Z'
                total: 2
    post:
      tags:
        - Collections
      summary: Create new collection
      operationId: createCollection
      description: >
        Create a new collection in a project.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateCollectionRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  name: products
                  fields:
                    - name: title
                      type: string
                      required: true
                    - name: price
                      type: number
                      required: true
                    - name: description
                      type: string
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  name: name_example
                  slug: slug_example
                  fields:
                    - name: name_example
                      type: string
                      required: true
                      unique: true
                      default: {}
                      validation: {}
                      ui: {}
                  permissions:
                    - role: role_example
                      actions:
                        - example_item
                      fields:
                        - example_item
                      condition: {}
                  settings: {}
      responses:
        '201':
          description: Collection created
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  collection:
                    $ref: '#/components/schemas/Collection'
              example:
                message: Collection created successfully
                collection:
                  _id: 74a2b3c4d5e6f7a8b9c0d1e2
                  name: users
                  slug: users
                  project: 65f1a2b3c4d5e6f7a8b9c0d1
                  fields:
                    - name: email
                      type: email
                      required: true
                  createdAt: '2024-01-15T10:00:00.000Z'
  /api/schemas/projects/{projectId}/collections/{collectionId}:
    get:
      tags:
        - Collections
      summary: Get single collection
      operationId: getCollection
      description: >
        Get collection details by ID.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: collectionId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Collection details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Collection'
              example:
                _id: 74a2b3c4d5e6f7a8b9c0d1e2
                name: users
                slug: users
                project: 65f1a2b3c4d5e6f7a8b9c0d1
                fields:
                  - name: email
                    type: email
                    required: true
                  - name: firstName
                    type: string
                    required: true
                createdAt: '2024-01-15T10:00:00.000Z'
                updatedAt: '2024-01-15T10:00:00.000Z'
    patch:
      tags:
        - Collections
      summary: Update collection
      operationId: updateCollection
      description: >
        Update collection configuration (name, fields, permissions).

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: collectionId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateCollectionRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  name: products_updated
                  fields:
                    - name: title
                      type: string
                      required: true
                    - name: price
                      type: number
                      required: true
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  name: name_example
                  fields:
                    - name: name_example
                      type: string
                      required: true
                      unique: true
                      default: {}
                      validation: {}
                      ui: {}
                  permissions:
                    - role: role_example
                      actions:
                        - example_item
                      fields:
                        - example_item
                      condition: {}
                  settings: {}
      responses:
        '200':
          description: Collection updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  collection:
                    $ref: '#/components/schemas/Collection'
              example:
                message: Collection updated successfully
                collection:
                  _id: 74a2b3c4d5e6f7a8b9c0d1e2
                  name: products_updated
                  slug: products-updated
                  project: 65f1a2b3c4d5e6f7a8b9c0d1
                  fields:
                    - name: title
                      type: string
                      required: true
                  updatedAt: '2024-01-15T11:00:00.000Z'
    delete:
      tags:
        - Collections
      summary: Delete collection
      operationId: deleteCollection
      description: >
        Delete a collection permanently. This is a destructive operation.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: collectionId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Collection deleted
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageResponse'
              example:
                message: Collection deleted successfully
  /api/data/projects/{projectId}/collections/{collectionId}/data:
    get:
      tags:
        - Data
      summary: List data in collection
      operationId: listData
      description: >
        List all documents in a collection.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: collectionId
          in: path
          required: true
          schema:
            type: string
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
            maximum: 100
        - name: sort
          in: query
          schema:
            type: string
            default: '-createdAt'
        - name: filter
          in: query
          schema:
            type: string
            description: JSON filter object
      responses:
        '200':
          description: Data list
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DataListResponse'
              example:
                data:
                  - _id: 696bbe5b99eeb7f929a93e0b
                    title: Laptop
                    price: 8500
                    description: High-performance laptop for developers
                    createdAt: '2026-01-17T16:52:43.541Z'
                    updatedAt: '2026-01-17T16:52:43.542Z'
                  - _id: 696bbe5c99eeb7f929a93e0c
                    title: Mouse
                    price: 25
                    description: Wireless mouse
                    createdAt: '2026-01-17T16:53:10.123Z'
                    updatedAt: '2026-01-17T16:53:10.123Z'
                pagination:
                  page: 1
                  limit: 20
                  total: 2
                  totalPages: 1
    post:
      tags:
        - Data
      summary: Create data in collection
      operationId: createData
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: collectionId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              description: Data object matching collection schema
            examples:
              standard:
                summary: Typical request
                value:
                  email: john.doe@example.com
                  firstName: John
                  lastName: Doe
                  role: developer
                  status: active
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  email: john.doe@example.com
                  firstName: John
                  lastName: Doe
                  role: developer
                  status: active
      responses:
        '201':
          description: Data created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DataResponse'
              example:
                message: Data created successfully
                data:
                  _id: 83b4c5d6e7f8a9b0c1d2e3f4
                  email: john.doe@mudbase.dev
                  firstName: John
                  lastName: Doe
                  role: developer
                  createdAt: '2024-01-15T10:00:00.000Z'
                  updatedAt: '2024-01-15T10:00:00.000Z'
  /api/data/projects/{projectId}/collections/{collectionId}/data/{documentId}:
    get:
      tags:
        - Data
      summary: Get single document
      operationId: getData
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: collectionId
          in: path
          required: true
          schema:
            type: string
        - name: documentId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Document data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DataResponse'
              example:
                _id: 83b4c5d6e7f8a9b0c1d2e3f4
                email: user@example.com
                firstName: John
                lastName: Doe
                createdAt: '2024-01-15T10:00:00.000Z'
                updatedAt: '2024-01-15T10:00:00.000Z'
    patch:
      tags:
        - Data
      summary: Update document
      operationId: updateData
      description: >
        Update a document in a collection.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: collectionId
          in: path
          required: true
          schema:
            type: string
        - name: documentId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              description: Partial data object for update
            examples:
              standard:
                summary: Typical request
                value:
                  firstName: Sarah
                  lastName: Chen
                  email: sarah.chen@example.com
                  role: admin
                  status: active
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  firstName: Sarah
                  lastName: Chen
                  email: sarah.chen@example.com
                  role: admin
                  status: active
      responses:
        '200':
          description: Data updated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DataResponse'
              example:
                message: Data updated successfully
                data:
                  _id: 83b4c5d6e7f8a9b0c1d2e3f4
                  firstName: Sarah
                  lastName: Chen
                  email: sarah.chen@example.com
                  role: admin
                  status: active
                  updatedAt: '2024-01-15T11:00:00.000Z'
    delete:
      tags:
        - Data
      summary: Delete document
      operationId: deleteData
      description: >
        Delete a document from a collection.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: collectionId
          in: path
          required: true
          schema:
            type: string
        - name: documentId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Data deleted
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageResponse'
              example:
                message: Data deleted successfully
  /api/bucket/projects/{projectId}/buckets:
    post:
      tags:
        - Buckets
      summary: Create a new bucket
      operationId: createBucket
      description: >
        Create a new storage bucket in a project.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateBucketRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  name: my-bucket
                  isPublic: false
                  settings: {}
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  name: name_example
                  isPublic: false
                  settings: {}
      responses:
        '201':
          description: Bucket created successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BucketResponse'
              example:
                success: true
                message: Bucket created successfully
                bucket:
                  _id: 65a1b2c3d4e5f6789012345a
                  name: my-bucket
                  project: 65f1a2b3c4d5e6f7a8b9c0d1
                  isPublic: false
                  settings: {}
                  createdAt: '2024-01-15T10:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          $ref: '#/components/responses/Conflict'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '500':
          $ref: '#/components/responses/InternalServerError'
    get:
      tags:
        - Buckets
      summary: List buckets in a project
      operationId: listBuckets
      description: >
        List all storage buckets in a project with pagination and search.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
        - name: search
          in: query
          schema:
            type: string
      responses:
        '200':
          description: List of buckets
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BucketListResponse'
              example:
                success: true
                buckets:
                  - _id: 65a1b2c3d4e5f6789012345a
                    name: my-bucket
                    project: 65f1a2b3c4d5e6f7a8b9c0d1
                    isPublic: false
                    createdAt: '2024-01-15T10:00:00.000Z'
                pagination:
                  page: 1
                  limit: 20
                  total: 1
                  totalPages: 1
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          $ref: '#/components/responses/Conflict'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/bucket/projects/{projectId}/buckets/{bucketId}:
    get:
      tags:
        - Buckets
      summary: Get bucket details
      operationId: getBucket
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: bucketId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Bucket details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BucketResponse'
              example:
                success: true
                message: Bucket retrieved successfully
                bucket:
                  _id: 65a1b2c3d4e5f6789012345a
                  name: my-bucket
                  project: 65f1a2b3c4d5e6f7a8b9c0d1
                  isPublic: false
                  settings: {}
                  createdAt: '2024-01-15T10:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          $ref: '#/components/responses/Conflict'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '500':
          $ref: '#/components/responses/InternalServerError'
    patch:
      tags:
        - Buckets
      summary: Update bucket
      operationId: updateBucket
      description: >
        Update bucket configuration (name, public/private status, settings).

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: bucketId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateBucketRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  name: my-bucket-updated
                  isPublic: true
                  settings: {}
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  name: name_example
                  isPublic: true
                  settings: {}
      responses:
        '200':
          description: Bucket updated successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BucketResponse'
              example:
                success: true
                message: Bucket updated successfully
                bucket:
                  _id: 65a1b2c3d4e5f6789012345a
                  name: my-bucket-updated
                  project: 65f1a2b3c4d5e6f7a8b9c0d1
                  isPublic: true
                  settings: {}
                  updatedAt: '2024-01-15T11:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          $ref: '#/components/responses/Conflict'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '500':
          $ref: '#/components/responses/InternalServerError'
    delete:
      tags:
        - Buckets
      summary: Delete bucket
      operationId: deleteBucket
      description: >
        Delete a storage bucket permanently. This is a destructive operation that will also delete all files in the
        bucket.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: bucketId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Bucket deleted successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageResponse'
              example:
                message: Bucket deleted successfully
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          $ref: '#/components/responses/Conflict'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/bucket/projects/{projectId}/buckets/{bucketId}/files:
    post:
      tags:
        - Files
      summary: Upload files to bucket
      operationId: uploadFiles
      description: >
        Upload one or more files to a storage bucket using multipart/form-data.

        Per-file size is limited by the org plan (`maxFileUploadBytes`) and bucket `maxFileSize`, whichever is stricter.
        Exceeding the limit returns **413**.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: bucketId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                files:
                  type: array
                  items:
                    type: string
                    format: binary
              required:
                - files
            encoding:
              files:
                contentType: application/octet-stream
            examples:
              standard:
                summary: Typical request
                value:
                  files:
                    - binary file content
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  files:
                    - example_item
      responses:
        '201':
          description: Files uploaded successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FileUploadResponse'
              example:
                message: Files uploaded successfully
                file:
                  _id: 685af8b85d73a104065b6a77
                  name: example.pdf
                  size: 1024000
                  mimeType: application/pdf
                  bucket: 65a1b2c3d4e5f6789012345a
                  url: https://storage.example.com/files/685af8b85d73a104065b6a77
                  createdAt: '2024-01-15T10:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          $ref: '#/components/responses/Conflict'
        '413':
          $ref: '#/components/responses/PayloadTooLarge'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '500':
          $ref: '#/components/responses/InternalServerError'
    get:
      tags:
        - Files
      summary: List files in bucket
      operationId: listFiles
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: bucketId
          in: path
          required: true
          schema:
            type: string
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
        - name: search
          in: query
          schema:
            type: string
        - name: type
          in: query
          schema:
            type: string
      responses:
        '200':
          description: List of files
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FileListResponse'
              example:
                files:
                  - _id: 685af8b85d73a104065b6a77
                    name: example.pdf
                    size: 1024000
                    mimeType: application/pdf
                    bucket: 65a1b2c3d4e5f6789012345a
                    url: https://storage.example.com/files/685af8b85d73a104065b6a77
                    createdAt: '2024-01-15T10:00:00.000Z'
                total: 1
                page: 1
                limit: 20
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          $ref: '#/components/responses/Conflict'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/bucket/projects/{projectId}/buckets/{bucketId}/files/{fileId}:
    get:
      tags:
        - Files
      summary: Get file metadata
      operationId: getFile
      description: >
        Get metadata for a specific file in a bucket.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: bucketId
          in: path
          required: true
          schema:
            type: string
        - name: fileId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: File metadata
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FileResponse'
              example:
                file:
                  _id: 685af8b85d73a104065b6a77
                  name: example.pdf
                  size: 1024000
                  mimeType: application/pdf
                  bucket: 65a1b2c3d4e5f6789012345a
                  url: https://storage.example.com/files/685af8b85d73a104065b6a77
                  createdAt: '2024-01-15T10:00:00.000Z'
                  updatedAt: '2024-01-15T10:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          $ref: '#/components/responses/Conflict'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '500':
          $ref: '#/components/responses/InternalServerError'
    delete:
      tags:
        - Files
      summary: Delete file
      operationId: deleteFile
      description: >
        Delete a file from a bucket permanently.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: bucketId
          in: path
          required: true
          schema:
            type: string
        - name: fileId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: File deleted successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageResponse'
              example:
                message: File deleted successfully
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          $ref: '#/components/responses/Conflict'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/files/{fileId}/download:
    get:
      tags:
        - Files
      summary: Generate a presigned URL for downloading a file
      description: >-
        Kept for SDK backward compatibility. The server routes file downloads at
        /api/files/download/{fileId} not this path. Callers should migrate to
        that endpoint. Returns a time-limited provider-signed URL for direct
        download. Server enforces RBAC before issuing the URL.
      deprecated: true
      operationId: downloadFile
      security:
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: fileId
          in: path
          required: true
          schema:
            type: string
        - name: token
          in: query
          schema:
            type: string
      responses:
        '200':
          description: Signed URL generated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SignedUrlResponse'
              example:
                success: true
                url: >-
                  https://my-bucket.storage.mudbase.dev/projects/123/default/abcd-file.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=...
                expiresIn: 3600
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          $ref: '#/components/responses/Conflict'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/files/upload/presigned:
    post:
      tags:
        - Files
      summary: Generate a presigned PUT URL for direct browser upload
      operationId: generatePresignedUpload
      description: >
        Issue a presigned PUT URL for clients to upload directly to object storage. The server stores the issued key
        with expiry and RBAC is enforced.

        PUT (not POST) is used because the object storage backend does not implement a POST-based upload API. The client must PUT the
        file body to `url` with the exact `headers` returned (a Content-Type mismatch fails with SignatureDoesNotMatch).
        `maxFileUploadBytes` is enforced server-side by `/api/files/upload/confirm` after the upload, not by the
        presigned URL itself.
      security:
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - projectId
                - originalName
              properties:
                projectId:
                  type: string
                bucket:
                  type: string
                  default: default
                originalName:
                  type: string
                contentType:
                  type: string
                isPublic:
                  type: boolean
                  default: false
            examples:
              standard:
                summary: Typical request
                value:
                  projectId: 65a1b2c3d4e5f6789012345a
                  bucket: default
                  originalName: invoice.pdf
                  contentType: application/pdf
                  isPublic: false
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  projectId: projectId_example
                  bucket: default
                  originalName: originalName_example
                  contentType: contentType_example
                  isPublic: false
      responses:
        '200':
          description: Presigned PUT URL
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PresignedPostResponse'
              example:
                key: 65a1b2c3d4e5f6789012345a/default/abcd-1234-invoice.pdf
                url: >-
                  https://my-bucket.storage.mudbase.dev/65a1b2c3d4e5f6789012345a/default/abcd-1234-invoice.pdf?X-Amz-Signature=...
                method: PUT
                headers:
                  Content-Type: application/pdf
                expiresIn: 3600
                maxFileUploadBytes: 52428800
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/files/upload/confirm:
    post:
      tags:
        - Files
      summary: Confirm direct upload (scan + finalize metadata)
      operationId: confirmDirectUpload
      description: >-
        After a client uploads directly to object storage using the presigned PUT URL, call this endpoint to have the server scan
        the object, create the File record, and optionally quarantine if infected.
      security:
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - key
                - projectId
              properties:
                key:
                  type: string
                  description: The object key returned when the presigned PUT URL was issued
                projectId:
                  type: string
                originalName:
                  type: string
                contentType:
                  type: string
                size:
                  type: integer
                bucket:
                  type: string
                isPublic:
                  type: boolean
            examples:
              standard:
                summary: Typical request
                value:
                  key: 65a1b2c3d4e5f6789012345a/default/abcd-1234-invoice.pdf
                  projectId: 65a1b2c3d4e5f6789012345a
                  originalName: invoice.pdf
                  contentType: application/pdf
                  size: 52312
                  isPublic: false
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  key: key_example
                  projectId: projectId_example
                  originalName: originalName_example
                  contentType: contentType_example
                  size: 1
                  bucket: bucket_example
                  isPublic: true
      responses:
        '201':
          description: File confirmed and metadata stored
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ConfirmUploadResponse'
              example:
                fileId: abcd1234ef567890
                status: ok
                scan:
                  status: clean
                  provider: virustotal
                  detections: 0
        '400':
          description: Bad request or file quarantined
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  details:
                    type: object
              example:
                message: File quarantined
                details:
                  fileId: abcd1234ef567890
                  status: quarantined
                  threat: EICAR-Test-Signature
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '413':
          $ref: '#/components/responses/PayloadTooLarge'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/bucket/projects/{projectId}/buckets/{bucketId}/files/{fileId}/signed-url:
    post:
      tags:
        - Files
      summary: Generate signed URL for file
      operationId: generateSignedUrl
      description: >
        Generate a time-limited signed URL for downloading a private file.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: bucketId
          in: path
          required: true
          schema:
            type: string
        - name: fileId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                expiresIn:
                  type: integer
                  default: 3600
                  example: 3600
            examples:
              standard:
                summary: Typical request
                value:
                  expiresIn: 3600
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  expiresIn: 3600
      responses:
        '200':
          description: Signed URL generated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SignedUrlResponse'
              example:
                success: true
                url: https://storage.example.com/files/685af8b85d73a104065b6a77?token=abc123xyz789&expires=1705312800
                expiresAt: '2024-01-15T11:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          $ref: '#/components/responses/Conflict'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/bucket/files/{fileId}/download:
    get:
      tags:
        - Files
      summary: Download file from bucket
      operationId: downloadBucketFile
      description: >
        Download a file from a bucket. For public files, no authentication is required.

        For private files, a download token (obtained via signed URL endpoint) is required in the query parameter.

        Accepts: Token-based authentication via query parameter (for private files), or no authentication (for public
        files).
      security: []
      parameters:
        - name: fileId
          in: path
          required: true
          schema:
            type: string
            example: 685af8b85d73a104065b6a77
        - name: token
          in: query
          schema:
            type: string
            description: Download token for private files
      responses:
        '200':
          description: File download
          content:
            application/octet-stream:
              schema:
                type: string
                format: binary
          headers:
            Content-Type:
              schema:
                type: string
            Content-Length:
              schema:
                type: integer
            Content-Disposition:
              schema:
                type: string
        '403':
          description: Access denied or invalid token
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                    example: Invalid or expired download token
              example:
                error: Invalid or expired download token
        '404':
          description: File not found
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                    example: File not found
              example:
                error: File not found
  /api/api-keys:
    get:
      tags:
        - API Keys
      summary: List API keys
      operationId: listApiKeys
      description: >
        List all API keys for the authenticated organization. Requires organization-level authentication (JWT Bearer
        token). API keys are not supported for this endpoint.
      security:
        - OrgBearerAuth: []
      responses:
        '200':
          description: API keys list
          content:
            application/json:
              schema:
                type: object
                properties:
                  apiKeys:
                    type: array
                    items:
                      $ref: '#/components/schemas/ApiKey'
                  total:
                    type: integer
              example:
                apiKeys:
                  - _id: 685ae8a785426b6a4190d5fc
                    name: Production API Key
                    project:
                      _id: 65f1a2b3c4d5e6f7a8b9c0d1
                      name: Mudbase Platform
                      slug: mudbase-platform
                    permissions:
                      - resource: database
                        actions:
                          - create
                          - read
                          - update
                          - delete
                      - resource: storage
                        actions:
                          - read
                    isActive: true
                    createdAt: '2024-01-15T10:00:00.000Z'
                  - _id: 685ae8a785426b6a4190d5fd
                    name: Development API Key
                    project:
                      _id: 685ad30be129932fbb7a1048
                      name: E-commerce API
                      slug: ecommerce-api
                    permissions:
                      - resource: database
                        actions:
                          - read
                    isActive: true
                    createdAt: '2024-01-16T14:30:00.000Z'
                total: 2
    post:
      tags:
        - API Keys
      summary: Create API key
      operationId: createApiKey
      description: >
        Create a new API key for a project with specified permissions. Requires organization-level authentication (JWT
        Bearer token). API keys are not supported for this endpoint.
      security:
        - OrgBearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateApiKeyRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  name: Production API Key
                  projectId: 65f1a2b3c4d5e6f7a8b9c0d1
                  permissions:
                    - resource: auth
                      actions:
                        - create
                        - read
                        - update
                        - delete
                    - resource: database
                      actions:
                        - create
                        - read
                        - update
                        - delete
                    - resource: storage
                      actions:
                        - create
                        - read
                        - update
                        - delete
                    - resource: functions
                      actions:
                        - create
                        - read
                        - update
                        - delete
                    - resource: realtime
                      actions:
                        - create
                        - read
                        - update
                        - delete
                    - resource: messaging
                      actions:
                        - create
                        - read
                        - update
                        - delete
                  expiresAt: '2026-12-31T23:59:59.000Z'
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  name: name_example
                  projectId: projectId_example
                  permissions:
                    - resource: auth
                      actions:
                        - example_item
                  rateLimit: {}
                  expiresAt: '2026-04-03T12:00:00.000Z'
      responses:
        '201':
          description: API key created
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  apiKey:
                    $ref: '#/components/schemas/ApiKeyWithSecret'
              example:
                message: API key created successfully
                apiKey:
                  _id: 685ae8a785426b6a4190d5fc
                  name: Production API Key
                  secret: mudbase_sk_live_<api-key-secret>
                  project:
                    _id: 65f1a2b3c4d5e6f7a8b9c0d1
                    name: Mudbase Platform
                    slug: mudbase-platform
                  permissions:
                    - resource: database
                      actions:
                        - create
                        - read
                        - update
                        - delete
                    - resource: storage
                      actions:
                        - read
                        - create
                        - update
                        - delete
                  isActive: true
                  createdAt: '2024-01-15T10:00:00.000Z'
                  expiresAt: '2025-12-31T23:59:59.000Z'
        '400':
          description: Validation failed (e.g. invalid permissions format, invalid or past expiresAt)
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                    example: Validation failed
                  details:
                    type: array
                    items:
                      type: string
                    example:
                      - '"permissions[0]" must be of type object'
                      - '"expiresAt" must be a valid date'
  /api/api-keys/{id}:
    patch:
      tags:
        - API Keys
      summary: Update API key
      operationId: updateApiKey
      description: >
        Update an API key's configuration (name, permissions, status). Requires organization-level authentication (JWT
        Bearer token). API keys are not supported for this endpoint.
      security:
        - OrgBearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateApiKeyRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  name: Updated API Key
                  permissions:
                    - resource: database
                      actions:
                        - read
                        - update
                    - resource: storage
                      actions:
                        - read
                  isActive: true
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  name: name_example
                  permissions:
                    - resource: auth
                      actions:
                        - example_item
                  rateLimit: {}
                  isActive: true
      responses:
        '200':
          description: API key updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  apiKey:
                    $ref: '#/components/schemas/ApiKey'
              example:
                message: API key updated successfully
                apiKey:
                  _id: 685ae8a785426b6a4190d5fc
                  name: Updated API Key
                  permissions:
                    - resource: database
                      actions:
                        - read
                        - update
                    - resource: storage
                      actions:
                        - read
                  project:
                    _id: 65f1a2b3c4d5e6f7a8b9c0d1
                    name: Mudbase Platform
                    slug: mudbase-platform
                  isActive: true
                  updatedAt: '2024-01-15T11:00:00.000Z'
    delete:
      tags:
        - API Keys
      summary: Delete API key
      operationId: deleteApiKey
      description: >
        Delete an API key. Requires organization-level authentication (JWT Bearer token). API keys are not supported for
        this endpoint.
      security:
        - OrgBearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: API key deleted
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageResponse'
              example:
                message: API key deleted successfully
  /api/api-keys/{id}/usage:
    get:
      tags:
        - API Keys
      summary: Get API key usage
      operationId: getApiKeyUsage
      description: >
        Get usage statistics for a specific API key including request count, rate limit status, and last used timestamp.
        Requires organization-level authentication (JWT Bearer token). API keys are not supported for this endpoint.
      security:
        - OrgBearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: API key usage statistics
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiKeyUsageResponse'
              example:
                usage:
                  requests: 1500
                  lastUsed: '2024-01-15T10:00:00.000Z'
                rateLimit:
                  limit: 10000
                  remaining: 8500
                  resetAt: '2024-01-16T00:00:00.000Z'
                isActive: true
                expiresAt: '2025-01-15T10:00:00.000Z'
  /api/api-keys/{id}/regenerate:
    post:
      tags:
        - API Keys
      summary: Regenerate API key secret
      operationId: regenerateApiKey
      description: >
        Regenerate the secret for an API key. The old secret will be invalidated immediately.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: API key regenerated
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  secret:
                    type: string
              example:
                message: API key secret regenerated successfully
                secret: mudbase_sk_live_<new-secret-value>
  /api/webhooks:
    get:
      tags:
        - Webhooks
      summary: List webhook delivery logs (organization)
      operationId: listWebhooks
      description: >
        Paginated **webhook delivery logs** for your organization (each row is one outbound HTTP attempt).

        Optional **`projectId`** query filters to a project that belongs to your org.


        Use each log document’s **`_id`** (MongoDB ObjectId) as **`webhookId`** when calling **`POST
        /api/webhooks/retry/{webhookId}`** after a failed delivery.

        Organization **JWT only** (`OrgBearerAuth`); project API keys are not accepted on this route.
      security:
        - OrgBearerAuth: []
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
        - name: status
          in: query
          schema:
            type: string
            enum:
              - pending
              - success
              - failed
              - retrying
        - name: event
          in: query
          schema:
            type: string
        - name: projectId
          in: query
          schema:
            type: string
            format: objectid
          description: Optional; restrict logs to this project (must belong to your org).
      responses:
        '200':
          description: Webhook delivery logs
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WebhookListResponse'
              examples:
                page:
                  summary: One delivery log
                  value:
                    webhooks:
                      - _id: 685af3992f9c4c96514247e9
                        org: 65a1b2c3d4e5f6789012345a
                        project: 65a1b2c3d4e5f6789012345b
                        webhookId: manual-1712140800123
                        event: custom.test
                        url: https://example.com/webhook
                        method: POST
                        status: success
                        attempts: 1
                        duration: 142
                        payload:
                          hello: world
                        response:
                          status: 200
                          body:
                            ok: true
                        headers:
                          Content-Type: application/json
                          User-Agent: MUDBASE-Webhook/1.0
                          X-MUDBASE-Event: custom.test
                          X-MUDBASE-Project: 65a1b2c3d4e5f6789012345b
                        createdAt: '2026-04-03T10:00:00.000Z'
                        updatedAt: '2026-04-03T10:00:00.200Z'
                    total: 1
                    page: 1
                    limit: 20
                    totalPages: 1
        '400':
          $ref: '#/components/responses/BadRequest'
        '403':
          $ref: '#/components/responses/Forbidden'
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/webhooks/projects/{projectId}:
    get:
      tags:
        - Webhooks
      summary: List webhook delivery logs (project)
      operationId: listProjectWebhookLogs
      description: >
        Same **`WebhookLog`** documents as **`GET /api/webhooks`**, scoped to **`projectId`** in the path.

        Accepts **org JWT**, **project JWT**, or **project API key** with project read access.


        Each item’s **`_id`** is the id returned as **`webhookId`** from **`POST /api/webhooks/trigger`** and used in
        **`POST /api/webhooks/retry/{webhookId}`**.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            format: objectid
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
        - name: status
          in: query
          schema:
            type: string
            enum:
              - pending
              - success
              - failed
              - retrying
        - name: event
          in: query
          schema:
            type: string
      responses:
        '200':
          description: Webhook delivery logs for the project
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WebhookListResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/webhooks/trigger:
    post:
      tags:
        - Webhooks
      summary: Manually trigger an outbound webhook
      operationId: triggerWebhook
      description: >
        Queues an HTTP delivery to **`url`** for **`projectId`** (must belong to your org). Creates a **`WebhookLog`**
        row, runs delivery, and returns the new log’s **`_id`**.


        **Response field `webhookId`:** This is the **MongoDB `_id` of the delivery log** (same as the log’s **`_id`**
        in list endpoints). It is **not** part of the request body and is **not** the project `webhookSecret` from
        **`PUT .../config`**.


        **Auth:** Org JWT, project JWT, or project API key with **project `update`** permission.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TriggerWebhookRequest'
            examples:
              standard:
                summary: POST JSON to your endpoint
                value:
                  projectId: 65a1b2c3d4e5f6789012345b
                  url: https://your-app.com/webhooks/mudbase
                  event: manual.test
                  payload:
                    message: Hello from Mudbase
              complete:
                summary: With explicit HTTP method
                value:
                  projectId: 65a1b2c3d4e5f6789012345b
                  url: https://your-app.com/webhooks/mudbase
                  event: manual.test
                  method: POST
                  payload:
                    orderId: ord_123
                    amount: 49.99
      responses:
        '200':
          description: Delivery queued; **`webhookId`** is the new log document **`_id`**
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TriggerWebhookResponse'
              examples:
                ok:
                  summary: Success
                  value:
                    message: Webhook triggered successfully
                    webhookId: 685af3992f9c4c96514247e9
        '400':
          description: Missing projectId, invalid project id, or invalid URL (SSRF guard)
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
        '404':
          description: Project not found or not in your org
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/webhooks/retry/{webhookId}:
    post:
      tags:
        - Webhooks
      summary: Retry a failed webhook delivery
      operationId: retryWebhook
      description: >
        **`webhookId`** (path) = **`WebhookLog._id`** (MongoDB ObjectId)—the same value returned as **`webhookId`** from
        **`POST /api/webhooks/trigger`** and as **`_id`** on **`GET /api/webhooks`** / **`GET
        /api/webhooks/projects/{projectId}`**.


        **Not** the string **`webhookId`** field stored on the log document (e.g. `manual-173…`); use the document
        **`_id`** for this path.


        Resets a non-success log to **pending** and re-delivers. **400** if status is already **`success`**.


        **Auth:** Organization JWT only; project API keys are not accepted.
      security:
        - OrgBearerAuth: []
      parameters:
        - name: webhookId
          in: path
          required: true
          schema:
            type: string
            format: objectid
          description: WebhookLog document `_id` (delivery log id).
      responses:
        '200':
          description: Retry queued
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RetryWebhookResponse'
              examples:
                ok:
                  summary: Retry started
                  value:
                    message: Webhook retry initiated
                    webhookId: 685af3992f9c4c96514247e9
        '400':
          description: Log already succeeded
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                    example: Webhook already succeeded
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: Log not found or not in your org
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/webhooks/projects/{projectId}/config:
    get:
      tags:
        - Webhooks
      summary: Get project webhook configuration
      operationId: getWebhookConfig
      description: >
        Get the current webhook URL, events, version, and transformations for a project.

        This is **where Mudbase POSTs event payloads**; it does **not** return a `webhookId`. Delivery ids
        (`WebhookLog._id`) come from **`POST /api/webhooks/trigger`** or automatic deliveries, and from **list logs**
        endpoints.


        Requires ProjectBearerAuth (JWT) or ApiKeyAuth (X-API-Key) with project read access.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            format: objectid
      responses:
        '200':
          description: Webhook configuration
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      webhookUrl:
                        type: string
                        nullable: true
                      webhookEvents:
                        type: array
                        items:
                          type: string
                      webhookVersion:
                        type: string
                      transformations:
                        type: array
                        description: Transformation rules applied to payloads
                        items:
                          type: object
                          properties:
                            type:
                              type: string
                              enum:
                                - jsonPath
                                - template
                                - fieldMap
                                - filter
                                - flatten
                                - version
                            config:
                              type: object
                              description: Transformation-specific configuration (shape depends on `type`)
                      hasSecret:
                        type: boolean
                        description: Whether a webhook secret is configured (value not returned)
              example:
                success: true
                data:
                  webhookUrl: https://your-app.com/webhooks/mudbase
                  webhookEvents:
                    - collection.insert
                    - collection.update
                  webhookVersion: '1.0'
                  transformations: []
                  hasSecret: true
        '404':
          description: Project not found
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  error:
                    type: string
        '500':
          $ref: '#/components/responses/InternalServerError'
    put:
      tags:
        - Webhooks
      summary: Create or update project webhook
      operationId: configureWebhook
      description: >
        Set or update the project webhook URL and options. This is how you **add** or **create** a webhook for a
        project:

        provide **webhookUrl** to enable delivery; omit or set to null to disable. Optionally set **webhookSecret**,

        **webhookEvents**, **webhookVersion**, and **transformations**. Plan limits (webhooks per project) apply when
        adding a new URL.

        Requires ProjectBearerAuth (JWT) or ApiKeyAuth (X-API-Key) with project update access.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            format: objectid
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                webhookUrl:
                  type: string
                  format: uri
                  nullable: true
                  description: URL to receive webhook payloads; set to null or omit to disable
                webhookSecret:
                  type: string
                  description: Optional secret for signing payloads (e.g. X-Webhook-Signature)
                webhookEvents:
                  type: array
                  items:
                    type: string
                  description: Event types to send (e.g. collection.insert, collection.update)
                webhookVersion:
                  type: string
                  description: Version string for payload format
                transformations:
                  type: array
                  description: Transformation rules to apply to payloads before delivery
                  items:
                    type: object
                    properties:
                      type:
                        type: string
                        enum:
                          - jsonPath
                          - template
                          - fieldMap
                          - filter
                          - flatten
                          - version
                      config:
                        type: object
                        description: Transformation-specific configuration (shape depends on `type`)
            examples:
              standard:
                summary: Typical request
                value:
                  webhookUrl: https://your-app.com/webhooks/mudbase
                  webhookSecret: your-secret
                  webhookEvents:
                    - collection.insert
                    - collection.update
                    - collection.delete
                  webhookVersion: '1.0'
                  transformations: []
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  webhookUrl: https://example.com/resource
                  webhookSecret: webhookSecret_example
                  webhookEvents:
                    - example_item
                  webhookVersion: webhookVersion_example
                  transformations: []
      responses:
        '200':
          description: Webhook configuration updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  data:
                    type: object
                    properties:
                      webhookUrl:
                        type: string
                        nullable: true
                      webhookEvents:
                        type: array
                        items:
                          type: string
                      webhookVersion:
                        type: string
                      transformations:
                        type: array
                        items:
                          type: object
                          properties:
                            type:
                              type: string
                              enum:
                                - jsonPath
                                - template
                                - fieldMap
                                - filter
                                - flatten
                                - version
                            config:
                              type: object
              example:
                success: true
                message: Webhook configuration updated
                data:
                  webhookUrl: https://your-app.com/webhooks/mudbase
                  webhookEvents:
                    - collection.insert
                    - collection.update
                  webhookVersion: '1.0'
                  transformations: []
        '403':
          description: Project webhook limit reached for your plan
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  error:
                    type: string
                  limit:
                    type: number
        '404':
          description: Project not found
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  error:
                    type: string
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/webhooks/projects/{projectId}/test-transformation:
    post:
      tags:
        - Webhooks
      summary: Test webhook transformation
      operationId: testWebhookTransformation
      description: |
        Apply transformation rules to a sample payload and return original and transformed payloads.
        Requires ProjectBearerAuth (JWT) or ApiKeyAuth (X-API-Key) with project update access.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            format: objectid
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - payload
                - transformations
              properties:
                payload:
                  type: object
                  description: Sample payload to transform
                transformations:
                  type: array
                  description: Transformation rules to apply
                  items:
                    type: object
                    properties:
                      type:
                        type: string
                        enum:
                          - jsonPath
                          - template
                          - fieldMap
                          - filter
                          - flatten
                          - version
                      config:
                        type: object
                        description: Transformation-specific configuration (shape depends on `type`)
            examples:
              standard:
                summary: Typical request
                value:
                  payload:
                    event: collection.insert
                    data:
                      name: Test
                  transformations: []
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  payload:
                    event: collection.insert
                    data:
                      name: Test
                  transformations: []
      responses:
        '200':
          description: Transformation result
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      original:
                        type: object
                      transformed:
                        type: object
              example:
                success: true
                data:
                  original:
                    event: collection.insert
                    data:
                      name: Test
                  transformed:
                    event: collection.insert
                    data:
                      name: Test
        '400':
          description: payload and transformations are required
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  error:
                    type: string
        '404':
          description: Project not found
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/webhooks/stats:
    get:
      tags:
        - Webhooks
      summary: Get webhook delivery statistics
      operationId: getWebhookStats
      description: >
        Aggregates **`WebhookLog`** rows for your organization over the last **`days`** (default 7).

        Optional **`projectId`** filters to a project in your org.


        Returns **`statusStats`** (counts and average duration per delivery **status**) and **`eventStats`** (counts and
        success rate per **event** name).


        **Auth:** Organization JWT only (`authRequired`).
      security:
        - OrgBearerAuth: []
      parameters:
        - name: projectId
          in: query
          schema:
            type: string
            format: objectid
          description: Optional; limit stats to this project.
        - name: days
          in: query
          schema:
            type: integer
            default: 7
      responses:
        '200':
          description: Aggregated webhook log statistics
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WebhookStatsResponse'
              examples:
                sample:
                  summary: Last 7 days
                  value:
                    statusStats:
                      - _id: success
                        count: 85
                        avgDuration: 210.5
                      - _id: failed
                        count: 10
                        avgDuration: 450.2
                      - _id: pending
                        count: 5
                        avgDuration: null
                    eventStats:
                      - _id: collection.insert
                        count: 40
                        successRate: 0.95
                      - _id: manual.test
                        count: 12
                        successRate: 1
                    period: 7 days
        '400':
          $ref: '#/components/responses/BadRequest'
        '404':
          description: Project not found or not in your org
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/functions/webhook/{projectId}:
    post:
      tags:
        - Functions
      summary: Trigger webhook functions
      operationId: triggerFunctionWebhook
      description: >
        Public endpoint for external services to trigger functions with `trigger.type: webhook`.

        No authentication required. Optionally verify using `X-Webhook-Secret` header (configure per project or via
        FUNCTION_WEBHOOK_SECRET).

        Rate limited to 120 requests per 15 minutes per IP (per-org adjustable).
      security: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            format: objectid
        - name: X-Webhook-Secret
          in: header
          required: false
          schema:
            type: string
          description: Optional webhook secret for verification
      requestBody:
        content:
          application/json:
            schema:
              type: object
              description: Payload sent to triggered functions
            examples:
              standard:
                summary: Typical JSON webhook body
                value:
                  event: user.created
                  userId: 507f1f77bcf86cd799439011
                  timestamp: '2026-04-03T12:00:00.000Z'
              complete:
                summary: Richer JSON payload (nested data)
                description: Any JSON your functions read from the webhook trigger context.
                value:
                  event: invoice.paid
                  id: evt_wh_2a8f9c1
                  amount_cents: 9999
                  currency: usd
                  customer:
                    email: customer@example.com
                    id: cus_abc123
                  metadata:
                    orderId: ord-456
                    source: billing_portal
          application/x-www-form-urlencoded:
            schema:
              type: object
            examples:
              standard:
                summary: Minimal form fields
                value:
                  event: ping
                  source: external_cron
              complete:
                summary: Form-style payload (e.g. Stripe-style keys)
                value:
                  type: checkout.session.completed
                  id: evt_1ABC
                  data[object][id]: cs_test_a1b2c3
                  data[object][customer_email]: payer@example.com
          text/plain:
            schema:
              type: string
            examples:
              standard:
                summary: Raw string body
                value: plain-text payload forwarded to functions
              complete:
                summary: Multi-line or structured text
                value: |
                  alert=cpu_high
                  host=app-01
                  value=94.2
      responses:
        '200':
          description: Functions triggered successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  triggered:
                    type: integer
                    description: Number of functions triggered
                  results:
                    type: array
                    items:
                      type: object
              examples:
                success:
                  summary: Successful trigger
                  value:
                    success: true
                    triggered: 2
                    results:
                      - functionId: 685af8b85d73a104065b6a77
                        success: true
                        result:
                          processed: true
                        executionTime: 45
                      - functionId: 685af8b85d73a104065b6a78
                        success: true
                        result:
                          processed: true
                        executionTime: 32
                noFunctions:
                  summary: No matching functions
                  value:
                    success: true
                    triggered: 0
                    results: []
        '400':
          description: Invalid project ID
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: false
                  error:
                    type: string
        '401':
          description: Invalid webhook secret
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: false
                  error:
                    type: string
                    example: Invalid webhook secret
        '404':
          description: Project not found
        '429':
          description: Rate limit exceeded
  /api/functions/projects/{projectId}/functions:
    get:
      tags:
        - Functions
      summary: List functions
      operationId: listFunctions
      description: |
        List serverless functions in a project with optional search and filters.
        Supports trigger types: http, event, document, file, webhook, cron, messaging.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
        - name: search
          in: query
          schema:
            type: string
          description: Search by name or description
        - name: triggerType
          in: query
          schema:
            type: string
            enum:
              - http
              - event
              - document
              - file
              - webhook
              - cron
              - messaging
          description: Filter by trigger type
        - name: isActive
          in: query
          schema:
            type: boolean
          description: Filter by active status (true/false)
      responses:
        '200':
          description: Functions list
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FunctionListResponse'
              examples:
                withFilters:
                  summary: List with search and filters
                  value:
                    success: true
                    data:
                      functions:
                        - _id: 685af8b85d73a104065b6a77
                          name: ProcessUserData
                          description: Process user data on create
                          trigger:
                            type: document
                            event: create
                            collectionId: 74a2b3c4d5e6f7a8b9c0d1e2
                          isActive: true
                          stats:
                            totalExecutions: 42
                            successful: 40
                            failed: 2
                            successRate: 95.24
                            avgExecutionTime: 125
                            lastRun: '2024-01-15T10:30:00.000Z'
                      pagination:
                        page: 1
                        limit: 20
                        total: 1
                        pages: 1
                webhookFunctions:
                  summary: Webhook-triggered functions
                  value:
                    success: true
                    data:
                      functions:
                        - _id: 685af8b85d73a104065b6a79
                          name: HandleStripeWebhook
                          trigger:
                            type: webhook
                            event: received
                          isActive: true
                      pagination:
                        page: 1
                        limit: 20
                        total: 1
                        pages: 1
    post:
      tags:
        - Functions
      summary: Create function
      operationId: createFunction
      description: |
        Create a new serverless function. Trigger types: http, document, file, webhook, cron, messaging.
        Sandbox globals available today: `payload`, `context`, `env`, `console`. Function code runs in an
        isolated worker with no ambient network or database access — it can only read its trigger payload,
        the `env` vars you configure, and return a JSON-serializable result; it cannot yet call back into
        your project's database, storage, or messaging APIs from inside the function body. If you
        need to read or write project data from a function, call the regular REST API (with your own API
        key) from your own backend in response to the function's returned result, rather than from within
        the function's own code.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateFunctionRequest'
            examples:
              documentTrigger:
                summary: Document create trigger
                value:
                  name: OnUserCreate
                  description: Process new users
                  code: |
                    // payload.document holds the created/updated document for this trigger
                    const created = payload.document?.data || {};
                    console.log('New user document:', created.email);
                    return { email: created.email || null, receivedAt: new Date().toISOString() };
                  trigger:
                    type: document
                    event: create
                    collectionId: 74a2b3c4d5e6f7a8b9c0d1e2
                  environment:
                    DEBUG: 'true'
              webhookTrigger:
                summary: Webhook trigger
                value:
                  name: HandleWebhook
                  code: |
                    return { received: payload.webhook?.body || payload };
                  trigger:
                    type: webhook
                    event: received
              cronTrigger:
                summary: Scheduled (cron) trigger
                value:
                  name: DailyReport
                  code: |
                    return { ran: new Date().toISOString() };
                  trigger:
                    type: cron
                    schedule: daily
              httpTrigger:
                summary: HTTP trigger
                value:
                  name: HttpWebhook
                  code: |
                    // payload.webhook contains headers/body for incoming HTTP
                    return { headers: payload.webhook?.headers || {}, body: payload.webhook?.body || {} };
                  trigger:
                    type: http
                    path: /projects/{projectId}/webhooks/custom
                    method: POST
              fileTrigger:
                summary: File trigger
                value:
                  name: ProcessFileUpload
                  code: |
                    // payload.file already contains the uploaded file's metadata for this trigger
                    const meta = payload.file || {};
                    return { fileId: meta.fileId, name: meta.name, size: meta.size };
                  trigger:
                    type: file
                    event: uploaded
              messagingTrigger:
                summary: Messaging trigger
                value:
                  name: OnMessageSent
                  code: >
                    // payload.message contains the sent message's own metadata for this trigger.

                    // Functions can't send email/SMS themselves yet — return a summary and have your

                    // own backend act on it (e.g. by polling this function's execution result).

                    const msg = payload.message || {};

                    return { messageId: msg.messageId, channel: msg.channel, summary: JSON.stringify(msg).slice(0, 200)
                    };
                  trigger:
                    type: messaging
                    event: sent
              customCronTrigger:
                summary: Custom cron expression
                value:
                  name: HourlyCleanup
                  code: |
                    // runs hourly
                    return { cleaned: true, at: new Date().toISOString() };
                  trigger:
                    type: cron
                    schedule: 0 * * * *
      responses:
        '201':
          description: Function created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FunctionResponse'
              examples:
                created:
                  summary: Function created
                  value:
                    success: true
                    data:
                      _id: 685af8b85d73a104065b6a77
                      name: OnUserCreate
                      trigger:
                        type: document
                        event: create
                        collectionId: 74a2b3c4d5e6f7a8b9c0d1e2
                      project: 65f1a2b3c4d5e6f7a8b9c0d1
                      isActive: true
                      versions:
                        - version: 1
                          comment: Initial version
                      createdAt: '2024-01-15T10:00:00.000Z'
  /api/functions/projects/{projectId}/functions/{functionId}:
    get:
      tags:
        - Functions
      summary: Get function
      operationId: getFunction
      description: Get function details by ID including createdBy/updatedBy.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: functionId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Function details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FunctionResponse'
              example:
                success: true
                data:
                  _id: 685af8b85d73a104065b6a77
                  name: OnUserCreate
                  description: Process new users
                  trigger:
                    type: document
                    event: create
                    collectionId: 74a2b3c4d5e6f7a8b9c0d1e2
                  project: 65f1a2b3c4d5e6f7a8b9c0d1
                  isActive: true
                  limits:
                    timeout: 30000
                    maxPayloadSize: 1048576
                    maxExecutionsPerMinute: 60
                    maxExecutionsPerHour: 1000
                  stats:
                    totalExecutions: 42
                    successful: 40
                    failed: 2
                    successRate: 95.24
                    avgExecutionTime: 125
                    lastRun: '2024-01-15T10:30:00.000Z'
                  createdBy:
                    _id: 685acbe0e129932fbb7a0fc2
                    name: John Doe
                    email: john@example.com
                  createdAt: '2024-01-15T10:00:00.000Z'
                  updatedAt: '2024-01-15T10:00:00.000Z'
        '404':
          description: Function not found
    put:
      tags:
        - Functions
      summary: Update function
      operationId: updateFunction
      description: Update function configuration. Code changes are versioned automatically.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: functionId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateFunctionRequest'
            examples:
              nameAndCode:
                summary: Update name and code
                value:
                  name: OnUserCreate v2
                  code: |
                    return { version: 2 };
                  versionComment: Add version tracking
              limits:
                summary: Update execution limits
                value:
                  limits:
                    timeout: 60000
                    maxPayloadSize: 2097152
                    maxExecutionsPerMinute: 120
      responses:
        '200':
          description: Function updated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FunctionResponse'
        '404':
          description: Function not found
    delete:
      tags:
        - Functions
      summary: Delete function
      operationId: deleteFunction
      description: Delete a function permanently. This is a destructive operation.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: functionId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Function deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
  /api/functions/projects/{projectId}/functions/{functionId}/activate:
    post:
      tags:
        - Functions
      summary: Activate function
      operationId: activateFunction
      description: Activate a deactivated function. Active functions can be triggered.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: functionId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Function activated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FunctionResponse'
  /api/functions/projects/{projectId}/functions/{functionId}/deactivate:
    post:
      tags:
        - Functions
      summary: Deactivate function
      operationId: deactivateFunction
      description: Deactivate a function. Deactivated functions will not be triggered.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: functionId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Function deactivated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FunctionResponse'
  /api/functions/projects/{projectId}/functions/{functionId}/execute:
    post:
      tags:
        - Functions
      summary: Execute function
      operationId: executeFunction
      description: |
        Manually execute a function with custom payload. Payload is merged with auto-injected trigger context.
        Rate limited (data mutation rate limiter). Enforces maxExecutionsPerMinute/maxExecutionsPerHour.

        This endpoint is asynchronous: it returns 202 immediately with an `executionId`, before the
        function has necessarily finished running. Poll
        `GET /api/functions/projects/{projectId}/functions/{functionId}/executions/{executionId}`
        until `status` leaves `queued`/`running` to get the real result, error, and duration.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: functionId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                payload:
                  type: object
                  description: Custom input merged with trigger context
            examples:
              simplePayload:
                summary: Simple payload
                value:
                  payload:
                    userId: 685acbe0e129932fbb7a0fc2
                    action: process
              documentContext:
                summary: Simulate document trigger payload
                value:
                  payload:
                    document:
                      _id: 83b4c5d6e7f8a9b0c1d2e3f4
                      collectionId: 74a2b3c4d5e6f7a8b9c0d1e2
                      data:
                        name: John
                        email: john@example.com
              webhookPayload:
                summary: Webhook-style payload
                value:
                  payload:
                    webhook:
                      headers:
                        content-type: application/json
                      body:
                        event: invoice.paid
                        invoiceId: inv_123
                        amount: 49.99
              fileUploadPayload:
                summary: File upload event payload
                value:
                  payload:
                    file:
                      fileId: file_abc123
                      bucket: default
                      url: https://cdn.example.com/project/default/file_abc123.jpg
                      originalName: photo.jpg
                      mimeType: image/jpeg
                      size: 345678
              cronPayload:
                summary: Cron/scheduled payload
                value:
                  payload:
                    cron:
                      schedule: daily
                      at: '2024-01-15T00:00:00.000Z'
              messagingPayload:
                summary: Messaging payload
                value:
                  payload:
                    message:
                      messageId: msg_123
                      senderId: user_123
                      chatId: chat_456
                      content:
                        text: Hello world
      responses:
        '202':
          description: Execution accepted (queued or run synchronously) — poll the executions endpoint for the outcome
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FunctionExecutionResponse'
              examples:
                accepted:
                  summary: Execution accepted
                  value:
                    success: true
                    data:
                      executionId: 8f3c2b1a-4e5d-6f7a-8b9c-0d1e2f3a4b5c
                      status: queued
        '400':
          description: Payload exceeds the function's configured max payload size
        '429':
          description: Rate limit exceeded (maxExecutionsPerMinute/maxExecutionsPerHour, or the data-mutation rate limiter)
  /api/functions/projects/{projectId}/functions/{functionId}/logs:
    get:
      tags:
        - Functions
      summary: Get function execution logs
      operationId: getFunctionLogs
      description: >-
        Get execution logs with pagination. Includes stats (totalExecutions, successful, failed, successRate,
        avgExecutionTime, lastRun).
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: functionId
          in: path
          required: true
          schema:
            type: string
        - name: limit
          in: query
          schema:
            type: integer
            default: 50
        - name: offset
          in: query
          schema:
            type: integer
            default: 0
      responses:
        '200':
          description: Function logs and stats
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FunctionLogsResponse'
              examples:
                withStats:
                  summary: Logs with stats
                  value:
                    success: true
                    data:
                      executions:
                        - executedAt: '2024-01-15T10:30:00.000Z'
                          executionTime: 125
                          success: true
                          result:
                            processed: 1
                          triggerType: document
                          triggerEvent: create
                          invokedBy: trigger
                        - executedAt: '2024-01-15T10:29:00.000Z'
                          executionTime: 0
                          success: false
                          error: Timeout
                          invokedBy: manual
                      stats:
                        totalExecutions: 42
                        successful: 40
                        failed: 2
                        successRate: 95.24
                        avgExecutionTime: 125
                        lastRun: '2024-01-15T10:30:00.000Z'
  /api/functions/projects/{projectId}/functions/{functionId}/retry/{executionIndex}:
    post:
      tags:
        - Functions
      summary: Retry failed execution
      operationId: retryFunctionExecution
      description: Retry a failed execution by its index (0-based) in the logs. Cannot retry successful executions.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: functionId
          in: path
          required: true
          schema:
            type: string
        - name: executionIndex
          in: path
          required: true
          schema:
            type: integer
          description: 0-based index of the execution in logs
      responses:
        '200':
          description: Retry result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FunctionExecutionResponse'
        '400':
          description: Cannot retry successful execution
        '404':
          description: Function or execution not found
  /api/functions/projects/{projectId}/functions/{functionId}/rollback:
    post:
      tags:
        - Functions
      summary: Rollback to previous version
      operationId: rollbackFunction
      description: Rollback function code to a previous version. Version number is required.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: functionId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - version
              properties:
                version:
                  type: integer
                  description: Version number to rollback to
            examples:
              standard:
                summary: Typical request
                value:
                  version: 2
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  version: 1
      responses:
        '200':
          description: Function rolled back
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FunctionResponse'
        '400':
          description: Version number is required
        '404':
          description: Function or version not found
  /api/functions/projects/{projectId}/functions/{functionId}/versions:
    get:
      tags:
        - Functions
      summary: Get function versions
      operationId: getFunctionVersions
      description: List all code versions for a function. Used for rollback.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: functionId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Function versions
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      versions:
                        type: array
                        items:
                          type: object
                          properties:
                            _id:
                              type: string
                            code:
                              type: string
                            version:
                              type: integer
                            createdAt:
                              type: string
                              format: date-time
                            createdBy:
                              type: string
                            comment:
                              type: string
              example:
                success: true
                data:
                  versions:
                    - _id: 65a1b2c3d4e5f6789012345c
                      version: 3
                      comment: Add validation
                      createdAt: '2024-01-15T12:00:00.000Z'
                    - _id: 65a1b2c3d4e5f6789012345b
                      version: 2
                      comment: Fix bug
                      createdAt: '2024-01-15T11:00:00.000Z'
                    - _id: 65a1b2c3d4e5f6789012345a
                      version: 1
                      comment: Initial version
                      createdAt: '2024-01-15T10:00:00.000Z'
        '404':
          description: Function not found
  /api/functions/projects/{projectId}/functions/{functionId}/simulate:
    post:
      tags:
        - Functions
      summary: Simulate trigger
      operationId: simulateFunctionTrigger
      description: |
        Test a function with simulated trigger context. Use to verify document, file, webhook, or cron payloads.
        Executes the function with the provided eventContext merged into the payload.

        Asynchronous, same pattern as Execute function: returns 202 immediately with an `executionId`.
        Poll `GET /api/functions/projects/{projectId}/functions/{functionId}/executions/{executionId}`
        for the real result.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: functionId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                trigger:
                  type: object
                  description: Simulated trigger (type, event)
                eventContext:
                  type: object
                  description: Simulated event context (document, file, webhook, message)
                payload:
                  type: object
                  description: Additional payload
            examples:
              documentCreate:
                summary: Simulate document create
                value:
                  trigger:
                    type: document
                    event: create
                  eventContext:
                    document:
                      _id: 83b4c5d6e7f8a9b0c1d2e3f4
                      collectionId: 74a2b3c4d5e6f7a8b9c0d1e2
                      data:
                        name: John
                        email: john@example.com
              webhookPayload:
                summary: Simulate webhook
                value:
                  trigger:
                    type: webhook
                    event: received
                  eventContext:
                    webhook:
                      headers:
                        content-type: application/json
                      body:
                        event: payment.completed
                        amount: 99.99
              fileUploaded:
                summary: Simulate file uploaded event
                value:
                  trigger:
                    type: file
                    event: uploaded
                  eventContext:
                    file:
                      fileId: file_abc123
                      bucket: default
                      url: https://cdn.example.com/project/default/file_abc123.jpg
                      originalName: photo.jpg
                      mimeType: image/jpeg
                      size: 345678
              cronRun:
                summary: Simulate cron schedule
                value:
                  trigger:
                    type: cron
                    schedule: daily
                  eventContext:
                    cron:
                      schedule: daily
                      at: '2024-01-15T00:00:00.000Z'
              messagingSent:
                summary: Simulate messaging event
                value:
                  trigger:
                    type: messaging
                    event: sent
                  eventContext:
                    message:
                      messageId: msg_123
                      senderId: user_123
                      chatId: chat_456
                      content:
                        text: Hello
      responses:
        '202':
          description: Simulation accepted — poll the executions endpoint for the outcome
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FunctionExecutionResponse'
              examples:
                accepted:
                  summary: Simulation accepted
                  value:
                    success: true
                    data:
                      executionId: 8f3c2b1a-4e5d-6f7a-8b9c-0d1e2f3a4b5c
                      status: queued
        '404':
          description: Function not found or inactive
  /api/functions/projects/{projectId}/functions/{functionId}/executions/{executionId}:
    get:
      tags:
        - Functions
      summary: Get execution status
      operationId: getFunctionExecution
      description: |
        Poll this after Execute function or Simulate trigger to get the real outcome — both of
        those endpoints return 202 immediately and do not carry the result themselves.
        `status` is one of `queued`, `provisioning`, `running`, `success`, `failed`, `timeout`;
        `result`/`error`/`durationMs`/`logs` are only populated once `status` leaves
        `queued`/`running`.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: functionId
          in: path
          required: true
          schema:
            type: string
        - name: executionId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Execution status
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FunctionExecutionStatusResponse'
              examples:
                success:
                  summary: Completed successfully
                  value:
                    success: true
                    data:
                      executionId: 8f3c2b1a-4e5d-6f7a-8b9c-0d1e2f3a4b5c
                      status: success
                      durationMs: 125
                      result:
                        processed: 1
                        count: 5
                      error: null
                      logs:
                        stdout: ''
                        stderr: ''
                        truncated: false
                        bytes: 0
                      createdAt: '2026-07-24T18:02:10.900Z'
                      startedAt: '2026-07-24T18:02:10.910Z'
                      completedAt: '2026-07-24T18:02:11.035Z'
                failed:
                  summary: Execution failed
                  value:
                    success: true
                    data:
                      executionId: 8f3c2b1a-4e5d-6f7a-8b9c-0d1e2f3a4b5c
                      status: failed
                      durationMs: 15
                      result: null
                      error: 'ReferenceError: x is not defined'
                      errorClass: ReferenceError
        '404':
          description: Execution not found
  /api/messaging/projects/{projectId}/messaging/devices:
    post:
      tags:
        - Messaging
      summary: Register a device push token
      operationId: registerDeviceToken
      description: >
        Register a device's push token with a project so it can receive push notifications. A client
        registers its token here first; the send endpoint (`/messaging/push`) only delivers to tokens
        that are registered to the project, so a caller cannot push to arbitrary or other-tenant tokens.


        Registration is idempotent - re-registering a token that already exists just refreshes it
        (updates `platform` and `lastSeenAt`) instead of creating a duplicate. Each project has a cap on
        the number of registered tokens; when the cap is reached, the least-recently-seen tokens are
        evicted to make room, so a register-on-launch call never fails.


        Push works out of the box with platform-managed credentials - no provider setup is required to
        start registering tokens and sending push.


        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or
        ApiKeyAuth (X-API-Key for programmatic access).
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DeviceRegisterRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  token: fMEGV8example-device-push-token-string9xY
                  platform: android
      responses:
        '201':
          description: Device token registered
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DeviceRegisteredResponse'
              example:
                success: true
                data:
                  token: fMEGV8example-device-push-token-string9xY
                  platform: android
                  lastSeenAt: '2024-01-15T10:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '403':
          $ref: '#/components/responses/FeatureNotAllowed'
        '429':
          description: Device registration rate limit exceeded
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  error:
                    type: string
    get:
      tags:
        - Messaging
      summary: List registered device tokens
      operationId: listDeviceTokens
      description: >
        List the device push tokens registered to a project, most-recently-seen first.


        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or
        ApiKeyAuth (X-API-Key for programmatic access).
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Registered device tokens
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DeviceListResponse'
              example:
                success: true
                data:
                  - token: fMEGV8example-device-push-token-string9xY
                    platform: android
                    lastSeenAt: '2024-01-15T10:00:00.000Z'
                    createdAt: '2024-01-10T08:30:00.000Z'
    delete:
      tags:
        - Messaging
      summary: Unregister a device push token
      operationId: unregisterDeviceToken
      description: >
        Remove a device push token from a project - call this on logout or when a token rotates, so the
        send endpoint stops delivering to it.


        The token to remove is sent in the request body. Removing a token that is not registered is a
        no-op and still returns 200 (with `removed: false`).


        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or
        ApiKeyAuth (X-API-Key for programmatic access).
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DeviceUnregisterRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  token: fMEGV8example-device-push-token-string9xY
      responses:
        '200':
          description: Device token removed (or already absent)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DeviceUnregisteredResponse'
              example:
                success: true
                data:
                  removed: true
  /api/messaging/projects/{projectId}/messaging/push:
    post:
      tags:
        - Messaging
      summary: Send push notification
      operationId: sendPushNotification
      description: >
        Send a push notification to one or more devices.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PushNotificationRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  tokens:
                    - device_token_123
                    - device_token_456
                  title: New Notification
                  body: You have a new message
                  data: {}
                  imageUrl: https://example.com/image.jpg
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  tokens:
                    - example_item
                  title: title_example
                  body: body_example
                  data: {}
                  imageUrl: imageUrl_example
      responses:
        '201':
          description: Push notification sent
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PushSentResponse'
              example:
                success: true
                data:
                  success: true
                  messageId: 65a1b2c3d4e5f6789012345c
                  successCount: 3
                  failureCount: 0
                  channels:
                    fcm:
                      successCount: 1
                      failureCount: 0
                    webPush:
                      successCount: 2
                      failureCount: 0
                      pruned: 0
        '403':
          $ref: '#/components/responses/FeatureNotAllowed'
        '429':
          description: Per-project messaging send rate limit exceeded
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  error:
                    type: string
                    example: messaging_rate_limited
                  message:
                    type: string
  /api/messaging/projects/{projectId}/messaging/email:
    post:
      tags:
        - Messaging
      summary: Send email
      operationId: sendEmail
      description: >
        Send an email message to one or more recipients.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/EmailRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  to: user@example.com
                  subject: Welcome to Mudbase
                  html: <h1>Welcome!</h1><p>Thank you for joining.</p>
                  text: Welcome! Thank you for joining.
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  to: {}
                  subject: subject_example
                  html: html_example
                  text: text_example
                  templateId: templateId_example
                  templateData: {}
      responses:
        '201':
          description: Email sent
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageSentResponse'
              example:
                success: true
                data:
                  _id: 65a1b2c3d4e5f6789012345d
                  type: email
                  status: sent
                  to: user@example.com
                  sentAt: '2024-01-15T10:00:00.000Z'
        '403':
          $ref: '#/components/responses/FeatureNotAllowed'
        '429':
          description: Per-project messaging send rate limit exceeded
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  error:
                    type: string
                    example: messaging_rate_limited
                  message:
                    type: string
  /api/messaging/projects/{projectId}/messaging/sms:
    post:
      tags:
        - Messaging
      summary: Send SMS
      operationId: sendSMS
      description: >
        Send an SMS message to one or more phone numbers. Uses project BYO SMS when configured; otherwise the platform
        SMS provider if set.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SMSRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  to: '+1234567890'
                  message: Your verification code is 123456
                  from: Mudbase
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  to: to_example
                  message: message_example
                  from: from_example
      responses:
        '201':
          description: SMS sent
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageSentResponse'
              example:
                success: true
                data:
                  _id: 65a1b2c3d4e5f6789012345f
                  type: sms
                  to: '+1234567890'
                  status: sent
                  createdAt: '2024-01-15T10:00:00.000Z'
        '403':
          $ref: '#/components/responses/FeatureNotAllowed'
        '429':
          description: Per-project messaging send rate limit exceeded
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  error:
                    type: string
                    example: messaging_rate_limited
                  message:
                    type: string
  /api/messaging/projects/{projectId}/messaging/sms-provider:
    get:
      tags:
        - Messaging
      summary: Get BYO SMS provider configuration (masked)
      operationId: getProjectSmsByo
      description: >
        Returns enabled flag, provider kind, default sender, and whether credentials are stored. Secrets are never
        returned.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: SMS BYO settings
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/ProjectSmsByoPublic'
              examples:
                twilio:
                  $ref: '#/components/examples/SmsByoGetTwilio'
                termii:
                  $ref: '#/components/examples/SmsByoGetTermii'
                africastalking:
                  $ref: '#/components/examples/SmsByoGetAfricasTalking'
                none:
                  $ref: '#/components/examples/SmsByoGetNone'
    patch:
      tags:
        - Messaging
      summary: Update BYO SMS provider credentials
      operationId: patchProjectSmsByo
      description: >
        Body `config` is provider-specific JSON stored encrypted per organization:

        - **twilio** — `accountSid`, `authToken` (required). Optional `from` sender override used if the send request
        does not specify `from` and `defaultFrom` is empty.

        - **termii** — `apiKey` (required). Optional `from` sender name (e.g. brand label).

        - **africastalking** — `username`, `apiKey` (both required). Optional `from` shortcode or sender ID.

        On enable, the API validates credentials with a lightweight ping (no SMS sent). See request body **Examples**
        for sample payloads.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ProjectSmsByoPatchRequest'
            examples:
              twilio:
                $ref: '#/components/examples/SmsByoPatchTwilio'
              termii:
                $ref: '#/components/examples/SmsByoPatchTermii'
              africastalking:
                $ref: '#/components/examples/SmsByoPatchAfricasTalking'
              disableByo:
                $ref: '#/components/examples/SmsByoPatchDisable'
      responses:
        '200':
          description: Updated configuration
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/ProjectSmsByoPublic'
              examples:
                twilio:
                  $ref: '#/components/examples/SmsByoGetTwilio'
                termii:
                  $ref: '#/components/examples/SmsByoGetTermii'
                africastalking:
                  $ref: '#/components/examples/SmsByoGetAfricasTalking'
                none:
                  $ref: '#/components/examples/SmsByoGetNone'
        '400':
          $ref: '#/components/responses/BadRequest'
  /api/messaging/projects/{projectId}/messaging/push-config:
    get:
      tags:
        - Messaging
      summary: Get bring-your-own push credentials status (masked)
      operationId: getProjectFcmConfig
      description: >-
        Returns whether this project has its own push provider credentials stored (encrypted). This is an
        optional, advanced override - push works out of the box with platform-managed credentials, so when
        no per-project credentials are stored, push is sent with the platform-managed credentials.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Bring-your-own push credentials flags
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      hasCredentials:
                        type: boolean
    patch:
      tags:
        - Messaging
      summary: Set or clear your own push service account (optional)
      operationId: patchProjectFcmConfig
      description: >
        Optional advanced step - push works out of the box with platform-managed credentials, so most projects
        never call this. Use it only to deliver push from your own push provider account. Body
        `serviceAccountJson` is the Firebase service account JSON you download from your own Firebase project
        (stored encrypted). Send `clear: true` to remove it and go back to the platform-managed credentials.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              oneOf:
                - type: object
                  required:
                    - serviceAccountJson
                  properties:
                    serviceAccountJson:
                      type: object
                      description: Firebase service account JSON (client_email, private_key, etc.)
                - type: object
                  required:
                    - clear
                  properties:
                    clear:
                      type: boolean
                      enum:
                        - true
            examples:
              standard:
                summary: Set BYO Firebase credentials (minimal service account shape)
                value:
                  serviceAccountJson:
                    type: service_account
                    project_id: my-firebase-project
                    private_key: |
                      -----BEGIN PRIVATE KEY-----
                      MIIE...
                      -----END PRIVATE KEY-----
                    client_email: firebase-adminsdk-xxxxx@my-firebase-project.iam.gserviceaccount.com
              complete:
                summary: Full service account JSON (typical Firebase console download)
                description: >
                  Same as downloading JSON from Firebase Console → Project settings → Service accounts. Stored
                  encrypted; omit or redact real secrets in docs.
                value:
                  serviceAccountJson:
                    type: service_account
                    project_id: my-firebase-project
                    private_key_id: a1b2c3d4e5f678901234567890abcdef12345678
                    private_key: |
                      -----BEGIN PRIVATE KEY-----
                      MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC...
                      -----END PRIVATE KEY-----
                    client_email: firebase-adminsdk-xxxxx@my-firebase-project.iam.gserviceaccount.com
                    client_id: '123456789012345678901'
                    auth_uri: https://accounts.google.com/o/oauth2/auth
                    token_uri: https://oauth2.googleapis.com/token
                    auth_provider_x509_cert_url: https://www.googleapis.com/oauth2/v1/certs
                    client_x509_cert_url: >-
                      https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-xxxxx%40my-firebase-project.iam.gserviceaccount.com
              clearCredentials:
                summary: Remove BYO credentials (use platform-managed credentials only)
                value:
                  clear: true
      responses:
        '200':
          description: Updated
        '400':
          $ref: '#/components/responses/BadRequest'
  /api/messaging/projects/{projectId}/messaging/web-push-config:
    get:
      tags:
        - Messaging
      summary: Get native Web Push (VAPID) configuration
      operationId: getProjectWebPushConfig
      description: >
        Read this project's native Web Push configuration. Native Web Push delivers browser push
        directly from Mudbase using the VAPID application-server key - no per-project push provider
        account is required. This returns whether native Web Push is enabled, whether a VAPID keypair
        has been provisioned, the public application-server key (when enabled), the RFC 8292 contact
        subject, and when the current keypair was generated. The private key is never returned.


        Native Web Push is off until you enable it (`PATCH` this endpoint). It sits alongside the
        device-token push path - a project can use either or both.


        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or
        ApiKeyAuth (X-API-Key for programmatic access).
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Native Web Push configuration
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WebPushConfigResponse'
              example:
                success: true
                data:
                  enabled: true
                  hasKeys: true
                  publicKey: BJ8example-vapid-public-key-base64url-encoded-application-server-key9xY
                  vapidSubject: mailto:push@yourapp.com
                  generatedAt: '2024-01-15T10:00:00.000Z'
        '404':
          $ref: '#/components/responses/NotFound'
    patch:
      tags:
        - Messaging
      summary: Update native Web Push (VAPID) configuration
      operationId: patchProjectWebPushConfig
      description: >
        Enable or disable native Web Push, rotate the VAPID keypair, or set the contact subject.


        - `enabled: true` turns native Web Push on and provisions a VAPID keypair the first time, so
        the public-key read path has a key to hand clients immediately. `enabled: false` turns it off.

        - `rotateKeys: true` regenerates the keypair. This invalidates existing browser subscriptions -
        clients must re-fetch the new public key and re-subscribe.

        - `subject` sets the RFC 8292 contact URI - a `mailto:` address or an `https` URL.


        Returns the same shape as `GET`. The private key is never returned.


        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or
        ApiKeyAuth (X-API-Key for programmatic access).
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/WebPushConfigPatchRequest'
            examples:
              enable:
                summary: Enable native Web Push (provisions a keypair)
                value:
                  enabled: true
                  subject: mailto:push@yourapp.com
              rotate:
                summary: Rotate the VAPID keypair
                value:
                  rotateKeys: true
              disable:
                summary: Disable native Web Push
                value:
                  enabled: false
      responses:
        '200':
          description: Updated native Web Push configuration
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WebPushConfigResponse'
              example:
                success: true
                data:
                  enabled: true
                  hasKeys: true
                  publicKey: BJ8example-vapid-public-key-base64url-encoded-application-server-key9xY
                  vapidSubject: mailto:push@yourapp.com
                  generatedAt: '2024-01-15T10:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/messaging/projects/{projectId}/messaging/web-push/public-key:
    get:
      tags:
        - Messaging
      summary: Get the Web Push public key (public)
      operationId: getProjectVapidPublicKey
      description: >
        Public read of the VAPID application-server public key a browser needs to subscribe with
        `pushManager.subscribe({ applicationServerKey })`. This is the one Web Push route that needs
        no authentication - the public key is designed to be exposed to browser clients. It returns
        only this project's own key.


        When the project has not enabled native Web Push, `enabled` is `false` and `publicKey` is
        `null`.
      security: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Public application-server key (or disabled)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WebPushPublicKeyResponse'
              examples:
                enabled:
                  summary: Native Web Push enabled
                  value:
                    success: true
                    data:
                      enabled: true
                      publicKey: BJ8example-vapid-public-key-base64url-encoded-application-server-key9xY
                disabled:
                  summary: Native Web Push not enabled
                  value:
                    success: true
                    data:
                      enabled: false
                      publicKey: null
        '404':
          $ref: '#/components/responses/NotFound'
  /api/messaging/projects/{projectId}/messaging/web-push/subscriptions:
    post:
      tags:
        - Messaging
      summary: Register a browser Web Push subscription
      operationId: registerWebPushSubscription
      description: >
        Register a browser `PushSubscription` (the `endpoint` plus the `p256dh` / `auth` keys returned
        by `pushManager.subscribe()`) so it becomes eligible to receive native Web Push. The send
        endpoint (`/messaging/push`) only delivers to subscriptions registered to the project, so a
        caller cannot push to arbitrary or other-tenant endpoints.


        Registration is idempotent - re-registering the same endpoint updates the existing row (keys
        rotate, `lastSeenAt` bumps) instead of creating a duplicate. Each project has a cap on the
        number of registered subscriptions; when the cap is reached, the least-recently-seen
        subscriptions are evicted to make room. Optionally associate the subscription with a `userId`
        (your end-user id, for targeted sends) and a `deviceId`.


        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or
        ApiKeyAuth (X-API-Key for programmatic access).
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/WebPushSubscribeRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  subscription:
                    endpoint: https://push-service.example.com/subscribe/abc123
                    keys:
                      p256dh: BEexample-p256dh-key-base64url
                      auth: example-auth-secret-base64url
                  userId: user_123
      responses:
        '201':
          description: Web Push subscription registered
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WebPushSubscribeResponse'
              example:
                success: true
                data:
                  endpoint: https://push-service.example.com/subscribe/abc123
                  userId: user_123
                  lastSeenAt: '2024-01-15T10:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '403':
          $ref: '#/components/responses/FeatureNotAllowed'
        '429':
          description: Subscription registration rate limit exceeded
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  error:
                    type: string
    get:
      tags:
        - Messaging
      summary: List registered Web Push subscriptions
      operationId: listWebPushSubscriptions
      description: >
        List the browser Web Push subscriptions registered to a project, most-recently-seen first. The
        encryption keys are never returned - only the endpoint and metadata.


        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or
        ApiKeyAuth (X-API-Key for programmatic access).
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Registered Web Push subscriptions
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WebPushSubscriptionListResponse'
              example:
                success: true
                data:
                  - endpoint: https://push-service.example.com/subscribe/abc123
                    userId: user_123
                    deviceId: ''
                    userAgent: Mozilla/5.0
                    disabled: false
                    lastSeenAt: '2024-01-15T10:00:00.000Z'
                    createdAt: '2024-01-10T08:30:00.000Z'
    delete:
      tags:
        - Messaging
      summary: Unregister a Web Push subscription
      operationId: removeWebPushSubscription
      description: >
        Remove a browser Web Push subscription - call this on unsubscribe or logout, so the send
        endpoint stops delivering to it. The subscription is identified by its `endpoint`, sent in the
        request body. Removing an endpoint that is not registered is a no-op and still returns 200
        (with `removed: false`).


        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or
        ApiKeyAuth (X-API-Key for programmatic access).
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/WebPushUnsubscribeRequest'
            examples:
              standard:
                summary: Typical request
                value:
                  endpoint: https://push-service.example.com/subscribe/abc123
      responses:
        '200':
          description: Subscription removed (or already absent)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WebPushUnsubscribeResponse'
              example:
                success: true
                data:
                  removed: true
  /api/messaging/projects/{projectId}/messaging/history:
    get:
      tags:
        - Messaging
      summary: Get message history
      operationId: getMessageHistory
      description: >
        Get message history (push, email, SMS) with filtering and pagination.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: type
          in: query
          schema:
            type: string
            enum:
              - push
              - email
              - sms
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
        - name: status
          in: query
          schema:
            type: string
            enum:
              - sent
              - failed
              - pending
      responses:
        '200':
          description: Message history
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageHistoryResponse'
              example:
                messages:
                  - _id: 65a1b2c3d4e5f6789012345f
                    type: email
                    to: user@example.com
                    subject: Welcome
                    status: sent
                    createdAt: '2024-01-15T10:00:00.000Z'
                total: 1
                page: 1
                limit: 20
        '403':
          $ref: '#/components/responses/FeatureNotAllowed'
  /api/messaging/projects/{projectId}/messaging/stats:
    get:
      tags:
        - Messaging
      summary: Get message statistics
      operationId: getMessageStats
      description: >
        Get messaging statistics including total messages, success rates, and breakdown by type (push, email, SMS).

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: startDate
          in: query
          schema:
            type: string
            format: date-time
        - name: endDate
          in: query
          schema:
            type: string
            format: date-time
      responses:
        '200':
          description: Message statistics
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageStatsResponse'
              example:
                stats:
                  total: 1000
                  sent: 950
                  failed: 50
                  byType:
                    email: 600
                    sms: 300
                    push: 100
                period: month
        '403':
          $ref: '#/components/responses/FeatureNotAllowed'
  /api/usage:
    get:
      tags:
        - Usage
      summary: Get organization usage
      operationId: getUsage
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: period
          in: query
          schema:
            type: string
            enum:
              - day
              - week
              - month
              - year
            default: month
        - name: startDate
          in: query
          schema:
            type: string
            format: date-time
        - name: endDate
          in: query
          schema:
            type: string
            format: date-time
      responses:
        '200':
          description: Usage statistics
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UsageStatsResponse'
              example:
                usage:
                  apiCalls: 50000
                  storage: 1073741824
                  bandwidth: 5368709120
                  databaseReads: 25000
                  databaseWrites: 5000
                period: month
                startDate: '2024-01-01T00:00:00.000Z'
                endDate: '2024-01-31T23:59:59.999Z'
        '503':
          $ref: '#/components/responses/ServiceUnavailable'
  /api/usage/warnings:
    get:
      tags:
        - Usage
      summary: Get usage warnings
      operationId: getUsageWarnings
      description: Returns usage warnings for the authenticated org (e.g. at 80% and 95% of plan limits). Requires org-level JWT.
      security:
        - OrgBearerAuth: []
      responses:
        '200':
          description: Usage warnings
          content:
            application/json:
              schema:
                type: object
                properties:
                  warnings:
                    type: array
                    items:
                      type: object
                      properties:
                        resource:
                          type: string
                        threshold:
                          type: number
                        current:
                          type: number
                        limit:
                          type: number
                        message:
                          type: string
        '400':
          description: Organization required
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/usage/projects/{projectId}:
    get:
      tags:
        - Usage
      summary: Get project usage
      operationId: getProjectUsageStats
      description: >
        Get usage statistics for a project (API calls, storage, bandwidth, database operations).

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: period
          in: query
          schema:
            type: string
            enum:
              - day
              - week
              - month
            default: month
      responses:
        '200':
          description: Project usage statistics
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ProjectUsageStatsResponse'
              example:
                usage:
                  apiCalls: 15000
                  storage: 52428800
                  bandwidth: 1073741824
                  databaseReads: 5000
                  databaseWrites: 2000
                period: month
                projectId: 65f1a2b3c4d5e6f7a8b9c0d1
  /api/usage/projects/{projectId}/summary:
    get:
      tags:
        - Usage
      summary: Project dashboard usage summary
      operationId: getProjectUsageSummary
      description: >
        Lightweight dashboard metrics for a project: requests today vs yesterday with % change, active users
        (24h/7d/30d),

        7d active-user trend, 14-day request volume series, per-project openapi-docs latency (today/7d), and uptime
        (30d) from org HTTP non-5xx when enough samples else DB heartbeats.

        Same auth as GET /api/usage/projects/{projectId} (org JWT, project JWT, or API key scoped to the project).
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Summary payload
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ProjectUsageSummaryResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/usage/trends:
    get:
      tags:
        - Usage
      summary: Get usage trends
      operationId: getUsageTrends
      description: >
        Get usage trends over time for the authenticated organization or project.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: days
          in: query
          schema:
            type: integer
            default: 30
      responses:
        '200':
          description: Usage trends
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UsageTrendsResponse'
              example:
                trends:
                  - date: '2024-01-01'
                    apiCalls: 1000
                    storage: 104857600
                  - date: '2024-01-02'
                    apiCalls: 1200
                    storage: 104857600
                days: 30
  /api/usage/overage:
    get:
      tags:
        - Usage
      summary: Get current overage line items
      operationId: getOverage
      description: |
        Returns overage line items for the authenticated organization's current billing period (current month).
        Used by dashboards and billing UIs. Requires org-level JWT (authRequired).
      security:
        - OrgBearerAuth: []
      responses:
        '200':
          description: Overage line items for current period
          content:
            application/json:
              schema:
                type: object
                properties:
                  overage:
                    type: array
                    items:
                      type: object
                      properties:
                        resource:
                          type: string
                          description: e.g. storage, apiCalls, realtimeMessages
                        units:
                          type: number
                        amount:
                          type: number
                        currency:
                          type: string
                        unit:
                          type: string
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '503':
          $ref: '#/components/responses/ServiceUnavailable'
  /api/search/projects/{projectId}/search:
    get:
      tags:
        - Search
      summary: Full-text search
      operationId: searchData
      description: >
        Perform full-text search across collections in a project.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: q
          in: query
          required: true
          schema:
            type: string
            description: Search query
        - name: collections
          in: query
          schema:
            type: string
            description: Comma-separated collection names
        - name: fields
          in: query
          schema:
            type: string
            description: Comma-separated field names
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
        - name: page
          in: query
          schema:
            type: integer
            default: 1
      responses:
        '200':
          description: Search results
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SearchResponse'
              example:
                success: true
                data:
                  results:
                    - collection: users
                      item:
                        _id: 83b4c5d6e7f8a9b0c1d2e3f4
                        email: john.doe@mudbase.dev
                        firstName: John
                        lastName: Doe
                        role: developer
                        score: 0.95
                      highlight:
                        firstName: <em>John</em>
                        lastName: Doe
                    - collection: users
                      item:
                        _id: 685ae1210136e73fa1dcaf37
                        email: jane.smith@mudbase.dev
                        firstName: Jane
                        lastName: Smith
                        role: admin
                        score: 0.82
                      highlight:
                        firstName: Jane
                        lastName: Smith
                  pagination:
                    page: 1
                    limit: 20
                    total: 2
                    totalPages: 1
                  query: john
                  searchTime: 45
  /api/search/projects/{projectId}/search/suggestions:
    get:
      tags:
        - Search
      summary: Get search suggestions
      operationId: getSearchSuggestions
      description: >
        Get search query suggestions based on partial input.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            example: 65f1a2b3c4d5e6f7a8b9c0d1
        - name: q
          in: query
          required: true
          schema:
            type: string
            description: Search query (min 2 characters, max 50)
            minLength: 2
            maxLength: 50
        - name: limit
          in: query
          schema:
            type: integer
            default: 10
            minimum: 1
            maximum: 20
      responses:
        '200':
          description: Search suggestions
          content:
            application/json:
              schema:
                type: object
                properties:
                  suggestions:
                    type: array
                    items:
                      type: string
              example:
                suggestions:
                  - john doe
                  - john smith
                  - johnny
  /api/search/projects/{projectId}/search/analytics:
    get:
      tags:
        - Search
      summary: Get search analytics
      operationId: getSearchAnalytics
      description: >
        Get search analytics including top queries, search volume, and performance metrics.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            example: 65f1a2b3c4d5e6f7a8b9c0d1
        - name: timeframe
          in: query
          schema:
            type: string
            enum:
              - 1d
              - 7d
              - 30d
            default: 7d
            description: Timeframe for analytics
      responses:
        '200':
          description: Search analytics
          content:
            application/json:
              schema:
                type: object
                properties:
                  totalSearches:
                    type: integer
                  topQueries:
                    type: array
                    items:
                      type: object
                      properties:
                        query:
                          type: string
                        count:
                          type: integer
                  searchesByCollection:
                    type: object
                  averageResponseTime:
                    type: number
              example:
                totalSearches: 1250
                topQueries:
                  - query: john
                    count: 45
                  - query: user
                    count: 32
                searchesByCollection:
                  users: 800
                  products: 450
                averageResponseTime: 45.2
  /api/monitoring/logs:
    get:
      tags:
        - Monitoring
      summary: Get audit logs
      operationId: getMonitoringLogs
      description: >
        Paginated audit trail for the org. Use **projectId** to scope to one project; **level=all** or **audit** for
        full activity feed.

        Each entry includes **activityTitle** and **activityDetail** for dashboard copy. Requires monitoring read
        permission.
      security:
        - OrgBearerAuth: []
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
            maximum: 500
        - name: projectId
          in: query
          description: Filter to this project (must belong to org)
          schema:
            type: string
        - name: userId
          in: query
          description: Filter to this user's audit entries
          schema:
            type: string
        - name: level
          in: query
          description: error|security|all|audit|low|medium|high|critical
          schema:
            type: string
            default: error
        - name: startDate
          in: query
          schema:
            type: string
            format: date-time
        - name: endDate
          in: query
          schema:
            type: string
            format: date-time
        - name: action
          in: query
          schema:
            type: string
        - name: resource
          in: query
          schema:
            type: string
      responses:
        '200':
          description: Audit logs with pagination
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MonitoringLogsResponse'
        '400':
          description: Invalid userId format
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          description: Project not found
  /api/monitoring/analytics:
    get:
      tags:
        - Monitoring
      summary: Get usage analytics (time series)
      operationId: getMonitoringAnalytics
      description: |
        Aggregates UsageStat by day/week/month. Optional **projectId** scopes to one project.
        Query **days** (1–90) for a rolling window (e.g. **days=14**); when set, overrides **period**.
      security:
        - OrgBearerAuth: []
      parameters:
        - name: projectId
          in: query
          schema:
            type: string
        - name: period
          in: query
          schema:
            type: string
            enum:
              - day
              - week
              - month
            default: month
        - name: granularity
          in: query
          schema:
            type: string
            enum:
              - day
              - week
              - month
            default: day
        - name: days
          in: query
          description: Rolling window in days (1–90); when set, period becomes last_N_days
          schema:
            type: integer
            minimum: 1
            maximum: 90
      responses:
        '200':
          description: Stats series and totals
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MonitoringAnalyticsResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          description: Project not found
  /api/monitoring/errors:
    get:
      tags:
        - Monitoring
      summary: Get error logs
      operationId: getMonitoringErrors
      security:
        - OrgBearerAuth: []
      responses:
        '200':
          description: Error logs
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/monitoring/performance:
    get:
      tags:
        - Monitoring
      summary: Get performance metrics
      operationId: getMonitoringPerformance
      description: |
        Response time stats from AuditLog where available. With **projectId**, falls back to UsageStat latency averages
        when audit data is sparse (**latencySource** may be **usage_stat**).
      security:
        - OrgBearerAuth: []
      parameters:
        - name: projectId
          in: query
          schema:
            type: string
        - name: period
          in: query
          schema:
            type: string
            enum:
              - hour
              - day
              - week
            default: hour
      responses:
        '200':
          description: Performance metrics
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MonitoringPerformanceResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          description: Project not found
  /api/monitoring/latency-insights:
    get:
      tags:
        - Monitoring
      summary: Latency insights (route templates, percentiles, impact scores)
      operationId: getMonitoringLatencyInsights
      description: >
        Per-process snapshot: normalized **routeKey** (METHOD + path template), **p50/p95/p99**, 4xx/5xx counts,

        **impactScore**, **alertsSuggested**, **rps**, **inFlight**, **eventLoopLagP99Ms**. One buffer per server
        instance.
      security:
        - OrgBearerAuth: []
      responses:
        '200':
          description: Latency insights payload
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/monitoring/queue-metrics:
    get:
      tags:
        - Monitoring
      summary: Usage metering queue job counts
      operationId: getMonitoringQueueMetrics
      description: BullMQ **usage-events** queue counts when `USE_METERING_QUEUE` and `REDIS_URL` are set.
      security:
        - OrgBearerAuth: []
      responses:
        '200':
          description: Queue depth snapshot
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/monitoring/alerts:
    get:
      tags:
        - Monitoring
      summary: List monitoring alerts
      operationId: listMonitoringAlerts
      security:
        - OrgBearerAuth: []
      responses:
        '200':
          description: List of alerts
        '401':
          $ref: '#/components/responses/Unauthorized'
    post:
      tags:
        - Monitoring
      summary: Create monitoring alert
      operationId: createMonitoringAlert
      description: Create a monitoring alert (plan limit alertsPerProject enforced).
      security:
        - OrgBearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name:
                  type: string
                condition:
                  type: string
                threshold:
                  type: number
                action:
                  type: string
                projectId:
                  type: string
            examples:
              standard:
                summary: Minimal / required fields
                value:
                  name: name_example
                  condition: condition_example
                  threshold: 0.01
                  action: action_example
                  projectId: projectId_example
              complete:
                summary: All request fields
                value:
                  name: name_example
                  condition: condition_example
                  threshold: 0.01
                  action: action_example
                  projectId: projectId_example
      responses:
        '201':
          description: Alert created
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: Alert limit reached for your plan
  /api/billing/plans:
    get:
      tags:
        - Billing
      summary: Get subscription tiers (org-level BaaS plans)
      description: >
        **Org-level BaaS plan catalog** (source of truth in paymentService.js). Returns Free, Basic ($12), Starter ($29), Growth
        ($69), Scale ($199), Enterprise. Use for pricing page and to get plan ids for POST /api/billing/org/checkout.
        Public; no auth required.

        Each plan includes id (free|basic|starter|growth|scale|enterprise), name, description, price (cents), priceYearly
        (cents, 2 months free), currency, limits, overages, enforcement.
      operationId: getSubscriptionTiers
      security: []
      responses:
        '200':
          description: Plan list
          content:
            application/json:
              schema:
                type: object
                properties:
                  plans:
                    type: array
                    items:
                      type: object
                      properties:
                        id:
                          type: string
                          example: starter
                        name:
                          type: string
                          example: Starter
                        description:
                          type: string
                        price:
                          type: number
                          description: Monthly price in cents
                          example: 2900
                        priceYearly:
                          type: number
                          description: Yearly price in cents (2 months free, ~16.67% off)
                        currency:
                          type: string
                          example: USD
                        priceId:
                          type: string
                          nullable: true
                        limits:
                          type: object
                        overages:
                          type: object
                        enforcement:
                          type: object
                          description: Per-resource enforcement (blocking, billing_only, etc.)
              example:
                plans:
                  - id: free
                    name: Free
                    price: 0
                    priceYearly: 0
                    currency: USD
                  - id: basic
                    name: Basic
                    price: 1200
                    priceYearly: 12000
                    currency: USD
                  - id: starter
                    name: Starter
                    price: 2900
                    priceYearly: 29000
                    currency: USD
                  - id: growth
                    name: Growth
                    price: 6900
                    priceYearly: 69000
                    currency: USD
  /api/billing/plans/{planId}:
    get:
      tags:
        - Billing
      summary: Get one subscription tier by id
      description: Returns a single org-level BaaS plan (free, basic, starter, growth, scale, enterprise). Public; no auth required.
      operationId: getSubscriptionTierById
      security: []
      parameters:
        - name: planId
          in: path
          required: true
          schema:
            type: string
          description: Plan id (free, basic, starter, growth, scale, enterprise)
      responses:
        '200':
          description: Plan details
          content:
            application/json:
              schema:
                type: object
                properties:
                  plan:
                    type: object
                    properties:
                      id:
                        type: string
                      name:
                        type: string
                      description:
                        type: string
                      price:
                        type: number
                      priceYearly:
                        type: number
                      currency:
                        type: string
                      limits:
                        type: object
                      overages:
                        type: object
        '404':
          description: Plan not found
  /api/billing/org/checkout:
    post:
      tags:
        - Billing
      summary: Initialize org-level BaaS plan payment (Basic, Starter, Growth, Scale)
      description: >
        **Org plan payment flow — Step 2.** Creates a payment link for the authenticated org to subscribe to a BaaS plan
        (basic, starter, growth, scale). Enterprise has no price; use contact-sales flow. Redirect the user to the returned
        link; after payment, call POST /api/billing/org/verify-payment with the tx_ref from the redirect. Requires
        org-level JWT.
      operationId: initializeOrgPlanCheckout
      security:
        - OrgBearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - planName
              properties:
                planName:
                  type: string
                  enum:
                    - basic
                    - starter
                    - growth
                    - scale
                  description: Plan id from GET /api/billing/plans (excludes free and enterprise)
                billingCycle:
                  type: string
                  enum:
                    - monthly
                    - yearly
                  default: monthly
                  description: Yearly = 2 months free (~16.67% discount)
                redirectUrl:
                  type: string
                  format: uri
                  description: Override redirect after payment (default FRONTEND_URL/billing/callback)
            examples:
              standard:
                summary: Typical request
                value:
                  planName: starter
                  billingCycle: monthly
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  planName: starter
                  billingCycle: monthly
                  redirectUrl: https://example.com/resource
      responses:
        '200':
          description: Payment link created
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      link:
                        type: string
                        description: Payment URL
                      txRef:
                        type: string
                        description: Reference for verify-payment (mudbase_org_...)
                      providerRef:
                        type: string
                      billingCycle:
                        type: string
                      amount:
                        type: number
                      amountCents:
                        type: number
        '400':
          description: Invalid planName or payment gateway not configured
        '401':
          description: Organization context required
  /api/billing/org/verify-payment:
    post:
      tags:
        - Billing
      summary: Verify org-level plan payment
      description: >
        **Org plan payment flow — Step 3.** Call after the user completes payment (redirect or webhook). Pass tx_ref (or
        reference) from the payment redirect. Updates org plan and billing; idempotent. No auth required (redirect
        callback can call this).
      operationId: verifyOrgPlanPayment
      security: []
      parameters:
        - name: tx_ref
          in: query
          schema:
            type: string
          description: Payment reference (mudbase_org_...) from checkout redirect
        - name: reference
          in: query
          schema:
            type: string
          description: Alias for tx_ref
      responses:
        '200':
          description: Payment verified and org plan updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  data:
                    type: object
                    properties:
                      plan:
                        type: string
                        description: New plan name (e.g. starter)
                      billingCycle:
                        type: string
                      orgId:
                        type: string
        '400':
          description: tx_ref required, invalid reference, or payment verification failed
  /api/billing/estimate:
    get:
      tags:
        - Billing
      summary: Get billing estimate and forecast
      operationId: getBillingEstimate
      description: |
        Returns current-month overage estimate and an optional end-of-month forecast for the authenticated organization.
        Includes spend limit settings (soft/hard) and whether usage is currently blocked. Requires org-level JWT.
      security:
        - OrgBearerAuth: []
      responses:
        '200':
          description: Billing estimate and forecast
          content:
            application/json:
              schema:
                type: object
                properties:
                  period:
                    type: string
                    description: Current month YYYY-MM
                  lineItems:
                    type: array
                    items:
                      type: object
                      properties:
                        resource:
                          type: string
                        units:
                          type: number
                        amount:
                          type: number
                        currency:
                          type: string
                        unit:
                          type: string
                  estimatedOverageCents:
                    type: number
                  estimatedOverage:
                    type: string
                    example: $12.50
                  forecastOverageCents:
                    type: number
                  forecastOverage:
                    type: string
                    example: $38.00
                  message:
                    type: string
                    nullable: true
                    description: Human-readable forecast when applicable
                  spendLimits:
                    type: object
                    properties:
                      softLimitCents:
                        type: number
                        nullable: true
                      hardLimitCents:
                        type: number
                        nullable: true
                      spendBlocked:
                        type: boolean
        '401':
          $ref: '#/components/responses/Unauthorized'
        '503':
          $ref: '#/components/responses/ServiceUnavailable'
  /api/billing/projects/{projectId}/plans:
    post:
      tags:
        - Billing
      summary: Create billing plan
      operationId: createPlan
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              description: >
                OpenAPI-style body normalized server-side into Plan.pricing (monthly/yearly amounts), features (objects
                with name/included), and optional limits/trial/metadata. Slug is derived from projectId + name unless a
                collision occurs.
              required:
                - name
                - price
                - currency
                - interval
              properties:
                name:
                  type: string
                  description: Display name; also used to generate a unique slug per project.
                description:
                  type: string
                price:
                  type: number
                  description: >
                    Amount for the chosen interval. The server fills the other billing period (e.g. yearly ≈ monthly ×
                    12 × 0.8 when interval is month).
                currency:
                  type: string
                  description: ISO currency code (stored lowercased).
                  example: USD
                interval:
                  type: string
                  enum:
                    - month
                    - year
                  description: Which period `price` applies to; drives pricing.monthly vs pricing.yearly.
                features:
                  type: array
                  description: |
                    Strings become `{ name, included: true }`. You may send full feature objects instead.
                  items:
                    oneOf:
                      - type: string
                      - type: object
                        properties:
                          name:
                            type: string
                          description:
                            type: string
                          included:
                            type: boolean
                            default: true
                          limit:
                            type: number
                            nullable: true
                            description: Usage cap for this feature; omit or null for unlimited.
                limits:
                  type: object
                  description: Plan caps; null or omitted fields mean unlimited where applicable.
                  properties:
                    apiCalls:
                      type: number
                      nullable: true
                    storage:
                      type: number
                      nullable: true
                    bandwidth:
                      type: number
                      nullable: true
                    users:
                      type: number
                      nullable: true
                    customLimits:
                      type: array
                      items:
                        type: object
                        properties:
                          name:
                            type: string
                          value:
                            type: number
                trial:
                  type: object
                  description: 'Defaults to `{ enabled: false, days: 7 }` when omitted.'
                  properties:
                    enabled:
                      type: boolean
                    days:
                      type: number
                isActive:
                  type: boolean
                  default: true
                isDefault:
                  type: boolean
                  default: false
                  description: Only one default plan per project is allowed server-side.
                sortOrder:
                  type: number
                  description: Lower numbers list first in UIs.
                metadata:
                  type: object
                  additionalProperties: true
                  description: Arbitrary key/value data stored on the plan document.
            examples:
              standard:
                summary: Typical plan (matches common curl)
                description: Required fields plus description and string feature list.
                value:
                  name: Pro Plan
                  description: Professional plan with advanced features
                  price: 29.99
                  currency: USD
                  interval: month
                  features:
                    - Unlimited API calls
                    - Priority support
                    - Advanced analytics
              complete:
                summary: Full request — all supported fields
                description: >
                  Yearly-priced plan with structured features, usage limits, trial, sort order, activation flags, and
                  metadata. Adjust projectId in the path (ObjectId or slug per your API).
                value:
                  name: Enterprise
                  description: Annual enterprise tier with SLA and dedicated support
                  price: 999
                  currency: USD
                  interval: year
                  features:
                    - name: Unlimited API calls
                      description: No rate limit on REST and realtime
                      included: true
                    - name: Dedicated support
                      included: true
                    - name: SSO (SAML)
                      included: true
                      limit: 50
                    - Custom integrations
                  limits:
                    apiCalls: 10000000
                    storage: 500
                    bandwidth: 2000
                    users: 100
                    customLimits:
                      - name: workspaces
                        value: 25
                  trial:
                    enabled: true
                    days: 14
                  isActive: true
                  isDefault: false
                  sortOrder: 10
                  metadata:
                    tier: enterprise
                    marketingSku: ENT-2026
                    notes: Synced from internal CRM id 48291
      responses:
        '201':
          description: Plan created
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  plan:
                    $ref: '#/components/schemas/Plan'
              example:
                message: Plan created successfully
                plan:
                  _id: 65a1b2c3d4e5f6789012345d
                  name: Pro Plan
                  description: Professional plan with advanced features
                  price: 29.99
                  currency: USD
                  interval: month
                  features:
                    - Unlimited API calls
                    - Priority support
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
    get:
      tags:
        - Billing
      summary: Get billing plans
      operationId: getPlans
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Plans list
          content:
            application/json:
              schema:
                type: object
                properties:
                  plans:
                    type: array
                    items:
                      $ref: '#/components/schemas/Plan'
                  total:
                    type: integer
              example:
                plans:
                  - _id: 65a1b2c3d4e5f6789012345d
                    name: Pro Plan
                    price: 29.99
                    currency: USD
                    interval: month
                total: 1
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/billing/projects/{projectId}/plans/{planId}:
    patch:
      tags:
        - Billing
      summary: Update billing plan
      operationId: updatePlan
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: planId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name:
                  type: string
                description:
                  type: string
                price:
                  type: number
                features:
                  type: array
                  items:
                    type: string
            examples:
              standard:
                summary: Typical request
                value:
                  name: Pro Plan Updated
                  description: Updated professional plan
                  price: 39.99
                  features:
                    - Unlimited API calls
                    - Priority support
                    - Advanced analytics
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  name: name_example
                  description: description_example
                  price: 0.01
                  features:
                    - example_item
      responses:
        '200':
          description: Plan updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  plan:
                    $ref: '#/components/schemas/Plan'
              example:
                message: Plan updated successfully
                plan:
                  _id: 65a1b2c3d4e5f6789012345d
                  name: Pro Plan Updated
                  description: Updated professional plan
                  price: 39.99
                  currency: USD
                  interval: month
                  features:
                    - Unlimited API calls
                    - Priority support
                    - Advanced analytics
                  updatedAt: '2024-01-15T11:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
    delete:
      tags:
        - Billing
      summary: Delete billing plan
      operationId: deletePlan
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: planId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Plan deleted
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageResponse'
              example:
                message: Plan deleted successfully
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/billing/public/projects/{projectId}/plans:
    get:
      tags:
        - Billing
      summary: Get public plans (no auth required)
      description: >
        **Customer subscription flow — Step 1.** Returns all active plans for the project. Use a plan's _id as planId in
        the checkout request. No authentication required (for pricing/checkout pages).
      operationId: getPublicPlans
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Public plans list
          content:
            application/json:
              schema:
                type: object
                properties:
                  plans:
                    type: array
                    items:
                      $ref: '#/components/schemas/Plan'
              example:
                plans:
                  - _id: 65a1b2c3d4e5f6789012345d
                    name: Pro Plan
                    price: 29.99
                    currency: USD
                    interval: month
                    features:
                      - Unlimited API calls
  /api/billing/public/projects/{projectId}/checkout:
    post:
      tags:
        - Billing
      summary: Create checkout session (fiat)
      description: >
        **Customer subscription flow — Step 2.** Creates a fiat checkout session. Request body must include planId (from
        GET public plans), billingCycle (monthly|yearly), and customerInfo.email. Redirect the user to **checkoutUrl**
        (same URL as authorizationUrl). After payment, call verify-payment with **reference** (mudbase_...).

        Response includes only fiat fields (no paymentAddress, paymentOptions, network, asset, or pmt_ references).
      operationId: createCheckoutSession
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
          description: Project ID
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - planId
                - billingCycle
                - customerInfo
              properties:
                planId:
                  type: string
                  description: Plan ID to subscribe to
                billingCycle:
                  type: string
                  enum:
                    - monthly
                    - yearly
                  description: Billing interval
                customerInfo:
                  type: object
                  required:
                    - email
                  properties:
                    email:
                      type: string
                      format: email
                    name:
                      type: string
                successUrl:
                  type: string
                  format: uri
                  description: Redirect URL after successful payment
                cancelUrl:
                  type: string
                  format: uri
                  description: Redirect URL if user cancels
            examples:
              standard:
                summary: Typical request
                value:
                  planId: 65a1b2c3d4e5f6789012345d
                  billingCycle: monthly
                  customerInfo:
                    email: customer@example.com
                    name: John Doe
                  successUrl: https://app.example.com/success
                  cancelUrl: https://app.example.com/cancel
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  planId: planId_example
                  billingCycle: monthly
                  customerInfo:
                    email: user@example.com
                    name: name_example
                  successUrl: https://example.com/resource
                  cancelUrl: https://example.com/resource
      responses:
        '200':
          description: Checkout session created
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      checkoutUrl:
                        type: string
                        format: uri
                        description: Hosted payment URL (same as authorizationUrl)
                      authorizationUrl:
                        type: string
                        format: uri
                        description: Hosted payment URL
                      accessCode:
                        type: string
                        description: Gateway access code
                      reference:
                        type: string
                        description: Transaction reference (mudbase_...) for verify-payment
                      amount:
                        type: number
                      currency:
                        type: string
              examples:
                fiat:
                  summary: Fiat response
                  value:
                    success: true
                    data:
                      checkoutUrl: https://pay.mudbase.dev/checkout/xxx
                      authorizationUrl: https://pay.mudbase.dev/checkout/xxx
                      accessCode: ACCESS_xxx
                      reference: mudbase_abc123xyz
                      amount: 29.99
                      currency: USD
        '400':
          description: Missing planId, billingCycle, or customerInfo.email
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
              example:
                error: planId, billingCycle, and customerInfo.email are required
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/billing/public/projects/{projectId}/checkout/{paymentId}:
    get:
      tags:
        - Billing
      summary: Get checkout payment details (not used for fiat billing)
      description: >
        **Fiat-only billing:** checkout is completed on the payment gateway's hosted page; there is no server-side
        payment intent to poll.

        The live API returns **404** for this route. Reserved for compatibility; do not rely on a success body for
        project billing.
      operationId: getCheckoutPayment
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: paymentId
          in: path
          required: true
          schema:
            type: string
          description: Opaque id from checkout (fiat billing does not expose pollable payment state here)
      responses:
        '404':
          description: Payment not found
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
              example:
                error: Payment not found
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/billing/public/projects/{projectId}/verify-payment:
    post:
      tags:
        - Billing
      summary: Verify payment and create subscription
      description: >
        **Customer subscription flow — Step 3.** Call after the user completes payment. Pass **reference** as query
        (?reference=mudbase_...). On success, a subscription is created. No auth required when using the platform
        gateway (mudbase_ refs). Org-level gateway verification may require JWT. References starting with pmt_ are
        rejected (crypto billing is not enabled on this API).
      operationId: verifyPayment
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: reference
          in: query
          required: true
          schema:
            type: string
          description: Payment transaction reference (mudbase_...)
      responses:
        '200':
          description: Payment verified and subscription created
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  data:
                    type: object
                    properties:
                      subscription:
                        type: object
                        properties:
                          _id:
                            type: string
                          status:
                            type: string
                            enum:
                              - active
                              - cancelled
                              - past_due
                          plan:
                            type: string
                          currentPeriodEnd:
                            type: string
                            format: date-time
              example:
                success: true
                message: Payment verified and subscription created
                data:
                  subscription:
                    _id: 65a1b2c3d4e5f6789012345e
                    status: active
                    plan: 65a1b2c3d4e5f6789012345d
                    currentPeriodEnd: '2026-04-02T00:00:00.000Z'
        '400':
          description: reference is required or organization context missing
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
              example:
                error: reference is required
        '403':
          description: Payment does not belong to your organization
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
              example:
                error: Payment does not belong to your organization
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/billing/projects/{projectId}/subscriptions:
    get:
      tags:
        - Billing
      summary: Get subscriptions
      operationId: getSubscriptions
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Subscriptions list
          content:
            application/json:
              schema:
                type: object
                properties:
                  subscriptions:
                    type: array
                    items:
                      type: object
                      properties:
                        _id:
                          type: string
                        status:
                          type: string
              example:
                subscriptions:
                  - _id: 65a1b2c3d4e5f6789012345e
                    status: active
                    plan: 65a1b2c3d4e5f6789012345d
                    customerEmail: customer@example.com
                    createdAt: '2024-01-15T10:00:00.000Z'
                total: 1
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/billing/subscriptions/{subscriptionId}/cancel:
    post:
      tags:
        - Billing
      summary: Cancel subscription
      operationId: cancelSubscription
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: subscriptionId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                cancelImmediately:
                  type: boolean
                  default: false
                  description: If true, cancel immediately; otherwise at period end
            examples:
              standard:
                summary: Typical request
                value:
                  cancelImmediately: false
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  cancelImmediately: false
      responses:
        '200':
          description: Subscription cancelled
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: Subscription cancelled successfully
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/billing/public/projects/{projectId}/subscription:
    get:
      tags:
        - Billing
      summary: Check subscription status (public)
      operationId: checkSubscription
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: email
          in: query
          required: true
          schema:
            type: string
            format: email
          description: Customer email to check subscription for
      responses:
        '200':
          description: Subscription status
          content:
            application/json:
              schema:
                type: object
                properties:
                  hasSubscription:
                    type: boolean
                  subscription:
                    type: object
                    properties:
                      status:
                        type: string
                      plan:
                        type: string
              example:
                hasSubscription: true
                subscription:
                  status: active
                  plan: 65a1b2c3d4e5f6789012345d
  /api/billing/public/projects/{projectId}/feature-access:
    get:
      tags:
        - Billing
      summary: Check feature access (public)
      operationId: checkFeatureAccess
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: email
          in: query
          required: true
          schema:
            type: string
            format: email
          description: Customer email
        - name: feature
          in: query
          required: true
          schema:
            type: string
          description: Feature slug to check access for
      responses:
        '200':
          description: Feature access status
          content:
            application/json:
              schema:
                type: object
                properties:
                  hasAccess:
                    type: boolean
                  reason:
                    type: string
              example:
                hasAccess: true
                reason: Active subscription
  /api/billing/public/projects/{projectId}/usage:
    post:
      tags:
        - Billing
      summary: Record usage (public)
      operationId: recordUsage
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - email
                - metric
                - quantity
              properties:
                email:
                  type: string
                  format: email
                  description: Customer email
                metric:
                  type: string
                  description: Usage metric name (e.g. api_calls, storage_mb)
                quantity:
                  type: number
                  description: Quantity to record
            examples:
              standard:
                summary: Typical request
                value:
                  email: customer@example.com
                  metric: api_calls
                  quantity: 150
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  email: user@example.com
                  metric: metric_example
                  quantity: 0.01
      responses:
        '200':
          description: Usage recorded
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageResponse'
              example:
                message: Usage recorded successfully
        '400':
          $ref: '#/components/responses/BadRequest'
  /api/billing/projects/{projectId}/dashboard:
    get:
      tags:
        - Billing
      summary: Get billing dashboard data
      operationId: getDashboard
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Dashboard data
          content:
            application/json:
              schema:
                type: object
                properties:
                  revenue:
                    type: number
                  subscriptions:
                    type: integer
                  activePlans:
                    type: integer
              example:
                revenue: 5000
                subscriptions: 25
                activePlans: 3
                monthlyRecurringRevenue: 2500
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          description: Project not found
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
  /api/billing/projects/{projectId}/invoices:
    get:
      tags:
        - Billing
      summary: List project invoices
      operationId: getInvoices
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Invoices list
          content:
            application/json:
              schema:
                type: object
                properties:
                  invoices:
                    type: array
                    items:
                      type: object
                      properties:
                        _id:
                          type: string
                        invoiceNumber:
                          type: string
                        status:
                          type: string
                        total:
                          type: number
                        currency:
                          type: string
                        dueDate:
                          type: string
                          format: date-time
                          nullable: true
                        paidAt:
                          type: string
                          format: date-time
                          nullable: true
                        createdAt:
                          type: string
                          format: date-time
                        hostedInvoiceUrl:
                          type: string
                          nullable: true
                  total:
                    type: integer
              example:
                invoices:
                  - _id: 65a1b2c3d4e5f6789012345f
                    invoiceNumber: INV-2026-001
                    status: paid
                    total: 29.99
                    currency: USD
                    dueDate: '2026-03-01T00:00:00.000Z'
                    paidAt: '2026-03-01T12:00:00.000Z'
                    createdAt: '2026-03-01T00:00:00.000Z'
                    hostedInvoiceUrl: null
                total: 1
        '401':
          $ref: '#/components/responses/Unauthorized'
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/billing/projects/{projectId}/invoices/{invoiceId}:
    get:
      tags:
        - Billing
      summary: Get single invoice
      operationId: getInvoice
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: invoiceId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Invoice details
          content:
            application/json:
              schema:
                type: object
                properties:
                  invoice:
                    type: object
                    properties:
                      _id:
                        type: string
                      invoiceNumber:
                        type: string
                      status:
                        type: string
                      total:
                        type: number
                      currency:
                        type: string
                      dueDate:
                        type: string
                        format: date-time
                        nullable: true
                      paidAt:
                        type: string
                        format: date-time
                        nullable: true
                      createdAt:
                        type: string
                        format: date-time
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          description: Invoice not found
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/billing/projects/{projectId}/invoices/{invoiceId}/download:
    get:
      tags:
        - Billing
      summary: Download invoice PDF
      operationId: downloadInvoice
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: invoiceId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Invoice PDF file or redirect URL
          content:
            application/pdf:
              schema:
                type: string
                format: binary
            application/json:
              schema:
                type: object
                properties:
                  url:
                    type: string
                    format: uri
                  message:
                    type: string
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          description: Invoice not found
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/billing/projects/{projectId}/invoices/{invoiceId}/export:
    get:
      tags:
        - Billing
      summary: Export invoice (e.g. PDF URL or file)
      operationId: exportInvoice
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: invoiceId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Export result (URL or file)
          content:
            application/json:
              schema:
                type: object
                properties:
                  url:
                    type: string
                    format: uri
                  message:
                    type: string
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          description: Invoice not found
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/orgs/{orgId}/payment-processing/enable:
    post:
      tags:
        - Billing
      summary: Submit payout onboarding for organization
      description: >-
        Validates and stores the org's payout account details, then queues the org for platform-admin review. This
        does not activate payments by itself; initialize-payment only starts succeeding once the org is approved. The
        required fields depend on the chosen country: call GET /payment-processing/countries first and collect
        exactly the fields that country's schema returns (bank code + account number for most African markets, plus a
        BVN for Nigeria, or routing number/sort code + account type + account holder name for the US/UK). Requires
        owner or admin role.
      operationId: enablePaymentProcessing
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - country
                - businessName
              properties:
                country:
                  type: string
                  description: >-
                    ISO-3166 alpha-2 payout country code, one of the codes returned by GET
                    /payment-processing/countries (e.g. NG, GH, KE, US, GB).
                businessName:
                  type: string
                businessMobile:
                  type: string
                  description: Optional, used for payout provider account notifications.
                accountBank:
                  type: string
                  description: Bank code, mobile-money network code, routing number, or sort code, depending on country.
                accountNumber:
                  type: string
                  description: Bank/mobile-money account number, IBAN, or similar, depending on country.
                bvn:
                  type: string
                  description: Required only when country is NG (Nigeria).
                accountType:
                  type: string
                  description: Required only when country is US (checking or savings).
                accountHolderName:
                  type: string
                  description: Required only when country is US or GB.
            examples:
              standard:
                summary: Typical request (NG)
                value:
                  country: NG
                  businessName: Acme Inc
                  accountBank: '044'
                  accountNumber: '0123456789'
                  bvn: '12345678901'
              complete:
                summary: All request fields (US, international)
                value:
                  country: US
                  businessName: Acme Inc
                  businessMobile: '+1234567890'
                  accountBank: '021000021'
                  accountNumber: '000123456789'
                  accountType: checking
                  accountHolderName: Acme Inc
      responses:
        '200':
          description: Onboarding submitted (or already enabled)
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  data:
                    type: object
                    properties:
                      onboarded:
                        type: boolean
                      alreadyEnabled:
                        type: boolean
                      approvalStatus:
                        type: string
                        description: >-
                          pending_review, approved, or rejected. Payments only start succeeding once this is approved,
                          poll GET /payment-processing/status to track it.
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/orgs/{orgId}/payment-processing/status:
    get:
      tags:
        - Billing
      summary: Get payout-onboarding status for organization
      description: >-
        Returns the current onboarding/approval state for the org's payout account. Poll this after calling
        enable, or before calling initialize-payment, to confirm the org is actually approved rather than assuming
        a 200 from enable means payments are live. Never returns the raw payout-account id, only whether one exists.
      operationId: getPaymentProcessingStatus
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Payout-onboarding status
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      onboarded:
                        type: boolean
                      enabled:
                        type: boolean
                        description: Whether payment collection is actually toggled on (implies approved).
                      approvalStatus:
                        type: string
                        description: not_submitted, pending_review, approved, or rejected.
                      status:
                        type: string
                        description: >-
                          Derived overall status for the console to render: not_onboarded, pending_review, rejected,
                          disabled, or active.
                      rejectionReason:
                        type: string
                        nullable: true
                      stablecoin:
                        type: object
                        description: Status of the separate stablecoin payment-links surface for this org (see Payment Links).
                        properties:
                          enabled:
                            type: boolean
                          settlementFiat:
                            type: string
                            nullable: true
                          walletCount:
                            type: integer
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
  /api/orgs/{orgId}/payment-processing/initialize-payment:
    post:
      tags:
        - Billing
      summary: Initialize fiat payment
      description: >-
        Creates a payment link. The customer pays; Mudbase charges a single all-in, cost-plus fee (see GET
        /payment-processing/fee-breakdown for the exact rate for a given country/method) and the org receives the
        remainder. Requires payment processing enabled and approved for the org.
      operationId: initializePayment
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - amount
                - customer
              properties:
                amount:
                  type: number
                  minimum: 0.01
                  description: Payment amount (e.g. USD)
                currency:
                  type: string
                  default: USD
                projectId:
                  type: string
                  description: Optional project scope
                customer:
                  type: object
                  required:
                    - email
                  properties:
                    email:
                      type: string
                    name:
                      type: string
                metadata:
                  type: object
                  description: title, description, redirectUrl, etc.
            examples:
              standard:
                summary: Typical request
                value:
                  amount: 100
                  currency: USD
                  customer:
                    email: buyer@example.com
                    name: Buyer Name
                  metadata:
                    title: 'Order #123'
                    description: Payment for order
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  amount: 0.01
                  currency: USD
                  projectId: projectId_example
                  customer:
                    email: email_example
                    name: name_example
                  metadata:
                    title: 'Order #123'
                    description: Payment for order
      responses:
        '200':
          description: Payment link and fee breakdown
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      link:
                        type: string
                      txRef:
                        type: string
                      providerRef:
                        type: string
                      amount:
                        type: number
                      currency:
                        type: string
                      orgReceives:
                        type: number
                        description: What the org nets after the single all-in Mudbase fee.
                      fee:
                        type: number
                        description: The single all-in Mudbase fee, in the same currency as amount.
                      feeRate:
                        type: number
                        description: The effective fee rate applied (fee / amount).
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/orgs/{orgId}/payment-processing/countries:
    get:
      tags:
        - Billing
      summary: List supported payout countries
      description: >-
        Returns the full supported payout-country set and each country's payout-account field schema. Drives a
        dynamic onboarding form: which fields to collect (bank code/routing number/sort code/IBAN, whether a BVN is
        required, whether a bank list or mobile-money network applies) comes straight from this response, so build
        your onboarding UI to render from it rather than hardcoding a country list.
      operationId: getPayoutCountries
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Supported countries and field schemas
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      countries:
                        type: array
                        items:
                          type: object
                          properties:
                            code:
                              type: string
                              description: ISO-3166 alpha-2 country code (e.g. NG, GH, KE, US, GB).
                            name:
                              type: string
                            currency:
                              type: string
                            banksListSupported:
                              type: boolean
                              description: Whether GET /payment-processing/banks returns a live bank list for this country.
                            mobileMoney:
                              type: boolean
                            international:
                              type: boolean
                              description: >-
                                True for a market whose settlement rail requires an account-level capability beyond
                                the standard local-rail onboarding (currently US, GB).
                            fields:
                              type: array
                              items:
                                type: object
                                properties:
                                  key:
                                    type: string
                                  label:
                                    type: string
                                  type:
                                    type: string
                                  required:
                                    type: boolean
                                  pattern:
                                    type: string
                                    nullable: true
                                  maxLength:
                                    type: integer
                                    nullable: true
                                  help:
                                    type: string
                                    nullable: true
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
  /api/orgs/{orgId}/payment-processing/banks:
    get:
      tags:
        - Billing
      summary: List settlement banks for a payout country
      description: >-
        Read-only lookup of the settlement-bank list for a country, only meaningful when that country's entry
        from GET /payment-processing/countries has banksListSupported: true. For a country where it is false,
        this returns an empty list and your onboarding form should fall back to the free-text bank/code field the
        countries response already describes for that country, rather than calling this endpoint.
      operationId: getPayoutBanks
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
        - name: country
          in: query
          required: true
          schema:
            type: string
          description: ISO-3166 alpha-2 payout country code, one of the codes from GET /payment-processing/countries.
      responses:
        '200':
          description: Bank list for the country
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      banksListSupported:
                        type: boolean
                      banks:
                        type: array
                        items:
                          type: object
                          properties:
                            code:
                              type: string
                            name:
                              type: string
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
  /api/orgs/{orgId}/payment-processing/fee-breakdown:
    get:
      tags:
        - Billing
      summary: Preview the fee for a given amount
      description: >-
        Returns the single all-in Mudbase fee, its effective rate, and what the org would net for the given amount,
        without creating a payment. Pass country/method/international to price a specific rail; omitting them uses a
        generic local-rail estimate. Never returns the underlying rail's own cost or any internal margin split.
      operationId: getFeeBreakdown
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
        - name: amount
          in: query
          required: true
          schema:
            type: number
            minimum: 0.01
        - name: currency
          in: query
          schema:
            type: string
            default: USD
        - name: country
          in: query
          schema:
            type: string
          description: ISO-3166 alpha-2 payout country code, one of the codes from GET /payment-processing/countries.
        - name: method
          in: query
          schema:
            type: string
            enum:
              - card
              - momo
              - bank_transfer
              - ussd
              - eft
            default: card
        - name: international
          in: query
          schema:
            type: boolean
            default: false
          description: Set true for a cross-border/international card, Apple Pay, or Google Pay.
      responses:
        '200':
          description: Fee breakdown
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      amount:
                        type: number
                      currency:
                        type: string
                      orgReceives:
                        type: number
                      fee:
                        type: number
                        description: The single all-in Mudbase fee.
                      feeRate:
                        type: number
                        description: The effective fee rate applied (fee / amount).
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/orgs/{orgId}/payment-processing/records:
    get:
      tags:
        - Billing
      summary: List fiat payment records for organization
      description: Paginated list of FiatPaymentRecord for this org (txRef, amount, orgReceives, status, paidAt).
      operationId: getPaymentRecords
      security:
        - OrgBearerAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema:
            type: string
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
        - name: status
          in: query
          schema:
            type: string
            enum:
              - pending
              - successful
              - failed
      responses:
        '200':
          description: Records and pagination
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      records:
                        type: array
                        items:
                          type: object
                          properties:
                            txRef:
                              type: string
                            amount:
                              type: number
                            orgReceives:
                              type: number
                            status:
                              type: string
                            paidAt:
                              type: string
                      pagination:
                        type: object
                        properties:
                          page:
                            type: integer
                          limit:
                            type: integer
                          total:
                            type: integer
                          pages:
                            type: integer
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/projects/{projectId}/payment-processing/initialize-payment:
    post:
      tags:
        - Billing
      summary: Initialize fiat payment (project-scoped)
      description: >-
        Same as org-level initialize-payment; projectId from path is used for scope and tx_ref. Resolves project to org
        and uses org's payment-processing subaccount.
      operationId: initializePaymentForProject
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - amount
                - customer
              properties:
                amount:
                  type: number
                  minimum: 0.01
                currency:
                  type: string
                  default: USD
                customer:
                  type: object
                  required:
                    - email
                  properties:
                    email:
                      type: string
                    name:
                      type: string
                metadata:
                  type: object
            examples:
              standard:
                summary: Minimal / required fields
                value:
                  amount: 0.01
                  customer:
                    email: email_example
              complete:
                summary: All request fields
                value:
                  amount: 0.01
                  currency: USD
                  customer:
                    email: email_example
                    name: name_example
                  metadata: {}
      responses:
        '200':
          description: Payment link and fee breakdown (same shape as org-level)
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '500':
          $ref: '#/components/responses/InternalServerError'
  /api/chat/projects/{projectId}/chats:
    post:
      tags:
        - Chat
      summary: Create new chat
      operationId: createChat
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - name
                - type
                - participants
              properties:
                name:
                  type: string
                description:
                  type: string
                type:
                  type: string
                  enum:
                    - direct
                    - group
                    - channel
                    - broadcast
                participants:
                  type: array
                  items:
                    type: string
                settings:
                  type: object
            examples:
              standard:
                summary: Typical request
                value:
                  name: Team Chat
                  description: Main team communication
                  type: group
                  participants:
                    - 685acbe0e129932fbb7a0fc2
                    - 685acbe0e129932fbb7a0fc3
                  settings: {}
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  name: name_example
                  description: description_example
                  type: direct
                  participants:
                    - example_item
                  settings: {}
      responses:
        '201':
          description: Chat created
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      _id:
                        type: string
                      name:
                        type: string
                      type:
                        type: string
                      participants:
                        type: array
                        items:
                          type: string
                      createdAt:
                        type: string
                        format: date-time
              example:
                success: true
                data:
                  _id: 65a1b2c3d4e5f6789012345f
                  name: Team Chat
                  type: group
                  participants:
                    - user: 65a1b2c3d4e5f6789012345
                      role: admin
                  createdAt: '2024-01-15T10:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
    get:
      tags:
        - Chat
      summary: Get user chats
      operationId: getUserChats
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
      responses:
        '200':
          description: User chats list
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      chats:
                        type: array
                        items:
                          type: object
                          properties:
                            _id:
                              type: string
                            name:
                              type: string
                            type:
                              type: string
                            lastMessage:
                              type: object
                              properties:
                                content:
                                  type: string
                            unreadCount:
                              type: integer
                      total:
                        type: integer
              example:
                success: true
                data:
                  chats:
                    - _id: 65a1b2c3d4e5f6789012345f
                      name: Team Chat
                      type: group
                      lastMessage:
                        content: Hello everyone
                      unreadCount: 2
                  total: 1
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/chat/projects/{projectId}/chats/{chatId}:
    get:
      tags:
        - Chat
      summary: Get chat details
      operationId: getChatDetails
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: chatId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Chat details
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      _id:
                        type: string
                      name:
                        type: string
                      participants:
                        type: array
                        items:
                          type: object
                          properties:
                            userId:
                              type: string
                            role:
                              type: string
              example:
                success: true
                data:
                  _id: 65a1b2c3d4e5f6789012345f
                  name: Team Chat
                  type: group
                  participants:
                    - userId: 685acbe0e129932fbb7a0fc2
                      role: admin
                  createdAt: '2024-01-15T10:00:00.000Z'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/chat/projects/{projectId}/me/chat-e2ee-key:
    put:
      tags:
        - Chat
      summary: Register chat E2EE identity public key
      description: |
        Stores your long-term public key for end-to-end encrypted chat (key agreement).
        Private keys never leave the client. Required for other participants to encrypt to you.
      operationId: putChatE2eeKey
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - identityPublicKey
              properties:
                identityPublicKey:
                  type: string
                  description: Base64-encoded public key (algorithm defined by client; opaque to server)
                keyVersion:
                  type: integer
                  description: Optional; defaults to incrementing stored version
            examples:
              standard:
                summary: Minimal / required fields
                value:
                  identityPublicKey: identityPublicKey_example
              complete:
                summary: All request fields
                value:
                  identityPublicKey: identityPublicKey_example
                  keyVersion: 1
      responses:
        '200':
          description: Key saved
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      identityPublicKey:
                        type: string
                      keyVersion:
                        type: integer
                      updatedAt:
                        type: string
                        format: date-time
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/chat/projects/{projectId}/chats/{chatId}/e2ee/participant-keys:
    get:
      tags:
        - Chat
      summary: List participant E2EE public keys
      description: Returns registered identity public keys for users in this chat (for client-side key distribution).
      operationId: getChatE2eeParticipantKeys
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: chatId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Participant keys
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        userId:
                          type: string
                        identityPublicKey:
                          type: string
                        keyVersion:
                          type: integer
                        updatedAt:
                          type: string
                          format: date-time
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/chat/projects/{projectId}/chats/{chatId}/messages:
    post:
      tags:
        - Chat
      summary: Send message
      operationId: sendMessage
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: chatId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - type
              properties:
                type:
                  type: string
                  enum:
                    - text
                    - image
                    - video
                    - audio
                    - file
                    - location
                    - contact
                content:
                  description: Plaintext body; omit when sending e2ee (use e2ee.ciphertext for E2EE text)
                  type: string
                e2ee:
                  description: Opaque end-to-end encrypted payload (base64 ciphertext). Server cannot decrypt. Only for type=text.
                  type: object
                  properties:
                    version:
                      type: integer
                      default: 1
                    scheme:
                      type: string
                      example: mudbase-e2ee-v1
                    ciphertext:
                      type: string
                      description: Base64-encoded ciphertext
                    nonce:
                      type: string
                    ephemeralPublicKey:
                      type: string
                    senderKeyId:
                      type: string
                replyTo:
                  type: string
                mentions:
                  type: array
                  items:
                    type: string
            examples:
              standard:
                summary: Typical request
                value:
                  type: text
                  content: Hello everyone!
                  replyTo: null
                  mentions: []
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  type: text
                  content: content_example
                  e2ee:
                    version: 1
                    scheme: mudbase-e2ee-v1
                    ciphertext: ciphertext_example
                    nonce: nonce_example
                    ephemeralPublicKey: ephemeralPublicKey_example
                    senderKeyId: senderKeyId_example
                  replyTo: replyTo_example
                  mentions:
                    - example_item
      responses:
        '201':
          description: Message sent
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      _id:
                        type: string
                      content:
                        type: string
                      sender:
                        type: string
                      createdAt:
                        type: string
                        format: date-time
              example:
                success: true
                data:
                  _id: 65a1b2c3d4e5f6789012345g
                  content: Hello everyone
                  sender: 65a1b2c3d4e5f6789012345
                  createdAt: '2024-01-15T10:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
    get:
      tags:
        - Chat
      summary: Get chat messages
      operationId: getChatMessages
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: chatId
          in: path
          required: true
          schema:
            type: string
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: limit
          in: query
          schema:
            type: integer
            default: 50
        - name: before
          in: query
          schema:
            type: string
            format: date-time
        - name: after
          in: query
          schema:
            type: string
            format: date-time
      responses:
        '200':
          description: Messages list
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      messages:
                        type: array
                        items:
                          type: object
                          properties:
                            _id:
                              type: string
                            content:
                              type: string
                            sender:
                              type: object
                              properties:
                                _id:
                                  type: string
                                firstName:
                                  type: string
                            createdAt:
                              type: string
                              format: date-time
                      total:
                        type: integer
              example:
                success: true
                data:
                  messages:
                    - _id: 65a1b2c3d4e5f6789012345g
                      content: Hello everyone
                      sender:
                        _id: 65a1b2c3d4e5f6789012345
                        firstName: John
                      createdAt: '2024-01-15T10:00:00.000Z'
                  total: 1
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/chat/projects/{projectId}/chats/{chatId}/messages/read:
    post:
      tags:
        - Chat
      summary: Mark messages as read
      operationId: markMessagesAsRead
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: chatId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - messageIds
              properties:
                messageIds:
                  type: array
                  items:
                    type: string
            examples:
              standard:
                summary: Typical request
                value:
                  messageIds:
                    - 65a1b2c3d4e5f6789012345g
                    - 65a1b2c3d4e5f6789012345h
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  messageIds:
                    - example_item
      responses:
        '200':
          description: Messages marked as read
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      modifiedCount:
                        type: integer
              example:
                success: true
                data:
                  modifiedCount: 5
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/chat/projects/{projectId}/chats/{chatId}/messages/{messageId}/reactions:
    post:
      tags:
        - Chat
      summary: Add reaction to message
      operationId: addReaction
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: chatId
          in: path
          required: true
          schema:
            type: string
        - name: messageId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - emoji
              properties:
                emoji:
                  type: string
            examples:
              standard:
                summary: Typical request
                value:
                  emoji: 👍
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  emoji: emoji_example
      responses:
        '200':
          description: Reaction added
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        emoji:
                          type: string
                        users:
                          type: array
                          items:
                            type: string
              example:
                success: true
                data:
                  - emoji: 👍
                    users:
                      - 65a1b2c3d4e5f6789012345
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
    delete:
      tags:
        - Chat
      summary: Remove reaction from message
      operationId: removeReaction
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: chatId
          in: path
          required: true
          schema:
            type: string
        - name: messageId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - emoji
              properties:
                emoji:
                  type: string
            examples:
              standard:
                summary: Typical request
                value:
                  emoji: 👍
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  emoji: emoji_example
      responses:
        '200':
          description: Reaction removed
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        emoji:
                          type: string
                        count:
                          type: integer
                        users:
                          type: array
                          items:
                            type: string
              example:
                success: true
                data:
                  - emoji: 👍
                    count: 2
                    users:
                      - 685acbe0e129932fbb7a0fc2
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/chat/projects/{projectId}/chats/{chatId}/messages/{messageId}:
    patch:
      tags:
        - Chat
      summary: Edit message
      operationId: editMessage
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: chatId
          in: path
          required: true
          schema:
            type: string
        - name: messageId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                content:
                  type: string
                  description: New plaintext (non-E2EE messages only)
                e2ee:
                  type: object
                  description: New opaque ciphertext (E2EE messages only)
                  properties:
                    version:
                      type: integer
                    scheme:
                      type: string
                    ciphertext:
                      type: string
                    nonce:
                      type: string
                    ephemeralPublicKey:
                      type: string
                    senderKeyId:
                      type: string
            examples:
              standard:
                summary: Typical request
                value:
                  content: Updated message content
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  content: content_example
                  e2ee:
                    version: 1
                    scheme: scheme_example
                    ciphertext: ciphertext_example
                    nonce: nonce_example
                    ephemeralPublicKey: ephemeralPublicKey_example
                    senderKeyId: senderKeyId_example
      responses:
        '200':
          description: Message edited
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      _id:
                        type: string
                      content:
                        type: string
                      isE2ee:
                        type: boolean
                      e2ee:
                        type: object
                      editedAt:
                        type: string
              example:
                success: true
                data:
                  _id: 65a1b2c3d4e5f6789012345g
                  content: Updated message content
                  editedAt: '2024-01-15T11:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
    delete:
      tags:
        - Chat
      summary: Delete message
      operationId: deleteMessage
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: chatId
          in: path
          required: true
          schema:
            type: string
        - name: messageId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Message deleted
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageResponse'
              example:
                message: Message deleted successfully
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/chat/projects/{projectId}/chats/{chatId}/participants:
    post:
      tags:
        - Chat
      summary: Add participant to chat
      operationId: addParticipant
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: chatId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - userId
              properties:
                userId:
                  type: string
                role:
                  type: string
                  enum:
                    - admin
                    - member
            examples:
              standard:
                summary: Typical request
                value:
                  userId: 685acbe0e129932fbb7a0fc2
                  role: member
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  userId: userId_example
                  role: admin
      responses:
        '200':
          description: Participant added
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      participants:
                        type: array
                        items:
                          type: object
                          properties:
                            userId:
                              type: string
                            role:
                              type: string
                            addedAt:
                              type: string
                              format: date-time
              example:
                success: true
                data:
                  participants:
                    - userId: 685acbe0e129932fbb7a0fc2
                      role: member
                      addedAt: '2024-01-15T11:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
    delete:
      tags:
        - Chat
      summary: Remove participant from chat
      operationId: removeParticipant
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: chatId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - userId
              properties:
                userId:
                  type: string
            examples:
              standard:
                summary: Typical request
                value:
                  userId: 685acbe0e129932fbb7a0fc2
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  userId: userId_example
      responses:
        '200':
          description: Participant removed
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageResponse'
              example:
                message: Participant removed successfully
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/integrations/templates:
    get:
      tags:
        - Integrations
      summary: Get integration templates
      operationId: getTemplates
      description: >
        Get available integration templates for third-party service connections.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      responses:
        '200':
          description: Integration templates list
          content:
            application/json:
              schema:
                type: object
                properties:
                  templates:
                    type: array
                    items:
                      type: object
                      properties:
                        _id:
                          type: string
                        name:
                          type: string
                        provider:
                          type: string
                        description:
                          type: string
              example:
                templates:
                  - _id: 65a1b2c3d4e5f6789012345h
                    name: Twitter API
                    provider: twitter
                    description: Twitter integration template
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/integrations/projects/{projectId}/integrations:
    get:
      tags:
        - Integrations
      summary: Get project integrations
      operationId: getIntegrations
      description: >
        List all integrations configured for a project.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Integrations list
          content:
            application/json:
              schema:
                type: object
                properties:
                  integrations:
                    type: array
                    items:
                      type: object
                      properties:
                        _id:
                          type: string
                        name:
                          type: string
                        provider:
                          type: string
                        status:
                          type: string
              example:
                integrations:
                  - _id: 65a1b2c3d4e5f6789012345i
                    name: Twitter Integration
                    provider: twitter
                    status: active
        '401':
          $ref: '#/components/responses/Unauthorized'
    post:
      tags:
        - Integrations
      summary: Create new integration
      operationId: createIntegration
      description: >
        Create a new third-party service integration for a project.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - name
                - provider
                - config
              properties:
                name:
                  type: string
                provider:
                  type: string
                config:
                  type: object
                credentials:
                  type: object
            examples:
              standard:
                summary: Typical request
                value:
                  name: Twitter Integration
                  provider: twitter
                  config: {}
                  credentials:
                    apiKey: your_api_key
                    apiSecret: your_api_secret
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  name: name_example
                  provider: provider_example
                  config: {}
                  credentials:
                    apiKey: your_api_key
                    apiSecret: your_api_secret
      responses:
        '201':
          description: Integration created
          content:
            application/json:
              schema:
                type: object
                properties:
                  integration:
                    type: object
              example:
                integration:
                  _id: 65a1b2c3d4e5f6789012345i
                  name: Twitter Integration
                  provider: twitter
                  project: 65f1a2b3c4d5e6f7a8b9c0d1
                  status: active
                  createdAt: '2024-01-15T10:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/integrations/projects/{projectId}/integrations/from-template:
    post:
      tags:
        - Integrations
      summary: Create integration from template
      operationId: createFromTemplate
      description: >
        Create a new integration using a pre-configured template.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - templateId
                - credentials
              properties:
                templateId:
                  type: string
                credentials:
                  type: object
                name:
                  type: string
            examples:
              standard:
                summary: Typical request
                value:
                  templateId: 65a1b2c3d4e5f6789012345h
                  credentials:
                    apiKey: your_api_key
                    apiSecret: your_api_secret
                  name: My Twitter Integration
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  templateId: templateId_example
                  credentials:
                    apiKey: your_api_key
                    apiSecret: your_api_secret
                  name: name_example
      responses:
        '201':
          description: Integration created from template
          content:
            application/json:
              schema:
                type: object
                properties:
                  integration:
                    type: object
              example:
                integration:
                  _id: 65a1b2c3d4e5f6789012345i
                  name: My Twitter Integration
                  provider: twitter
                  project: 65f1a2b3c4d5e6f7a8b9c0d1
                  status: active
                  createdAt: '2024-01-15T10:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/integrations/projects/{projectId}/integrations/import:
    post:
      tags:
        - Integrations
      summary: Import integration
      operationId: importIntegration
      description: >
        Import an integration configuration from exported data.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - integrationData
              properties:
                integrationData:
                  type: object
            examples:
              standard:
                summary: Typical request
                value:
                  integrationData:
                    name: Imported Integration
                    provider: custom
                    config: {}
                    credentials: {}
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  integrationData:
                    name: Imported Integration
                    provider: custom
                    config: {}
                    credentials: {}
      responses:
        '201':
          description: Integration imported
          content:
            application/json:
              schema:
                type: object
                properties:
                  integration:
                    type: object
              example:
                integration:
                  _id: 65a1b2c3d4e5f6789012345i
                  name: Imported Integration
                  provider: twitter
                  project: 65f1a2b3c4d5e6f7a8b9c0d1
                  status: active
                  createdAt: '2024-01-15T10:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/integrations/projects/{projectId}/integrations/{integrationId}:
    get:
      tags:
        - Integrations
      summary: Get integration details
      operationId: getIntegration
      description: >
        Get details of a specific integration.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: integrationId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Integration details
          content:
            application/json:
              schema:
                type: object
                properties:
                  integration:
                    type: object
                    properties:
                      _id:
                        type: string
                      name:
                        type: string
                      provider:
                        type: string
                      project:
                        type: string
                      status:
                        type: string
                      config:
                        type: object
                      createdAt:
                        type: string
                        format: date-time
              example:
                integration:
                  _id: 65a1b2c3d4e5f6789012345i
                  name: Twitter Integration
                  provider: twitter
                  project: 65f1a2b3c4d5e6f7a8b9c0d1
                  status: active
                  config: {}
                  createdAt: '2024-01-15T10:00:00.000Z'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
    patch:
      tags:
        - Integrations
      summary: Update integration
      operationId: updateIntegration
      description: >
        Update integration configuration (name, config, credentials).

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: integrationId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name:
                  type: string
                config:
                  type: object
                credentials:
                  type: object
            examples:
              standard:
                summary: Typical request
                value:
                  name: Updated Integration
                  config: {}
                  credentials:
                    apiKey: updated_api_key
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  name: name_example
                  config: {}
                  credentials:
                    apiKey: updated_api_key
      responses:
        '200':
          description: Integration updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  integration:
                    type: object
              example:
                integration:
                  _id: 65a1b2c3d4e5f6789012345i
                  name: Updated Integration
                  provider: twitter
                  updatedAt: '2024-01-15T11:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
    delete:
      tags:
        - Integrations
      summary: Delete integration
      operationId: deleteIntegration
      description: >
        Delete an integration from a project.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: integrationId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Integration deleted
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MessageResponse'
              example:
                message: Integration deleted successfully
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/integrations/projects/{projectId}/integrations/{integrationId}/test:
    post:
      tags:
        - Integrations
      summary: Test integration
      operationId: testIntegration
      description: >
        Test an integration connection and configuration.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: integrationId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                endpoint:
                  type: string
                method:
                  type: string
                params:
                  type: object
            examples:
              standard:
                summary: Typical request
                value:
                  endpoint: /api/v1/test
                  method: GET
                  params: {}
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  endpoint: endpoint_example
                  method: method_example
                  params: {}
      responses:
        '200':
          description: Integration test result
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
              example:
                success: true
                data:
                  status: 200
                  response: {}
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/integrations/projects/{projectId}/integrations/{integrationId}/execute:
    post:
      tags:
        - Integrations
      summary: Execute integration
      operationId: executeIntegration
      description: >
        Execute an integration action (API call) with specified endpoint and parameters.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: integrationId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - endpoint
                - method
              properties:
                endpoint:
                  type: string
                method:
                  type: string
                  enum:
                    - GET
                    - POST
                    - PUT
                    - PATCH
                    - DELETE
                params:
                  type: object
                body:
                  type: object
            examples:
              standard:
                summary: Typical request
                value:
                  endpoint: /api/v1/users
                  method: GET
                  params: {}
                  body: {}
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  endpoint: endpoint_example
                  method: GET
                  params: {}
                  body: {}
      responses:
        '200':
          description: Integration executed
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
              example:
                success: true
                data:
                  status: 200
                  response: {}
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/integrations/projects/{projectId}/integrations/{integrationId}/export:
    get:
      tags:
        - Integrations
      summary: Export integration
      operationId: exportIntegration
      description: >
        Export integration configuration for backup or migration.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: integrationId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Integration export data
          content:
            application/json:
              schema:
                type: object
                properties:
                  integration:
                    type: object
              example:
                integration:
                  _id: 65a1b2c3d4e5f6789012345i
                  name: Twitter Integration
                  provider: twitter
                  config: {}
                  credentials: {}
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/integrations/projects/{projectId}/integrations/{integrationId}/usage:
    get:
      tags:
        - Integrations
      summary: Get integration usage statistics
      operationId: getUsageStats
      description: >
        Get usage statistics for an integration (total calls, success/failure rates).

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: integrationId
          in: path
          required: true
          schema:
            type: string
        - name: period
          in: query
          schema:
            type: string
            enum:
              - day
              - week
              - month
            default: month
      responses:
        '200':
          description: Usage statistics
          content:
            application/json:
              schema:
                type: object
                properties:
                  stats:
                    type: object
                    properties:
                      totalCalls:
                        type: integer
                      successCalls:
                        type: integer
                      failedCalls:
                        type: integer
              example:
                stats:
                  totalCalls: 150
                  successCalls: 145
                  failedCalls: 5
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/projects/{projectId}/fee-settings:
    post:
      tags:
        - Project Fees
      summary: ~~Create or update project fee settings~~ (deprecated)
      deprecated: true
      operationId: createOrUpdateFeeSettings
      description: >
        Create or update fee settings for a project. Configure transaction fees, payout addresses, and thresholds for
        supported cryptocurrencies.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - currency
              properties:
                currency:
                  type: string
                  enum:
                    - BTC
                    - ETH
                    - BNB
                    - LTC
                    - SOL
                    - TRX
                    - USDT-ETH
                    - USDT-BSC
                    - USDT-TRX
                    - USDT-SOL
                enabled:
                  type: boolean
                feeAmount:
                  type: number
                  minimum: 0
                payoutAddress:
                  type: string
                payoutThreshold:
                  type: number
                  minimum: 0
            examples:
              standard:
                summary: Typical request
                value:
                  currency: BTC
                  enabled: true
                  feeAmount: 0.00005
                  payoutAddress: bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh
                  payoutThreshold: 0.001
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  currency: BTC
                  enabled: true
                  feeAmount: 0
                  payoutAddress: payoutAddress_example
                  payoutThreshold: 0
      responses:
        '200':
          description: Fee settings updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  data:
                    type: object
              example:
                success: true
                message: Project fee settings updated successfully
                data:
                  enabled: true
                  feeAmount: 0.00005
                  payoutAddress: bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh
                  payoutThreshold: 0.001
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
    get:
      tags:
        - Project Fees
      summary: ~~Get project fee settings~~ (deprecated)
      deprecated: true
      operationId: getFeeSettings
      description: >
        Get all fee settings configured for a project.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Fee settings
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
              example:
                success: true
                data:
                  BTC:
                    enabled: true
                    feeAmount: 0.00005
                    payoutAddress: bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh
                    payoutThreshold: 0.001
                    addressVerified: true
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/projects/{projectId}/fee-settings/{currency}:
    patch:
      tags:
        - Project Fees
      summary: ~~Update currency fee settings~~ (deprecated)
      deprecated: true
      operationId: updateCurrencyFeeSettings
      description: >
        Update fee settings for a specific cryptocurrency in a project.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: currency
          in: path
          required: true
          schema:
            type: string
            enum:
              - BTC
              - ETH
              - BNB
              - LTC
              - SOL
              - TRX
              - USDT-ETH
              - USDT-BSC
              - USDT-TRX
              - USDT-SOL
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                enabled:
                  type: boolean
                feeAmount:
                  type: number
                payoutAddress:
                  type: string
                payoutThreshold:
                  type: number
            examples:
              standard:
                summary: Typical request
                value:
                  enabled: true
                  feeAmount: 0.05
                  payoutAddress: bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh
                  payoutThreshold: 0.1
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  enabled: true
                  feeAmount: 0.01
                  payoutAddress: payoutAddress_example
                  payoutThreshold: 0.01
      responses:
        '200':
          description: Currency fee settings updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  data:
                    type: object
              example:
                success: true
                message: Currency fee settings updated successfully
                data:
                  enabled: true
                  feeAmount: 0.05
                  payoutAddress: bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh
                  payoutThreshold: 0.1
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/projects/{projectId}/fee-settings/{currency}/verify-address:
    post:
      tags:
        - Project Fees
      summary: ~~Initiate address verification~~ (deprecated)
      deprecated: true
      operationId: initiateAddressVerification
      description: >
        Initiate verification process for a payout address. Requires sending a small test transaction to verify
        ownership.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: currency
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Verification initiated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  verificationStatus:
                    type: string
              example:
                success: true
                message: Verification initiated. Please send a small transaction to the provided address.
                verificationStatus: pending
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/projects/{projectId}/fee-settings/{currency}/confirm-verification:
    post:
      tags:
        - Project Fees
      summary: ~~Confirm address verification~~ (deprecated)
      deprecated: true
      operationId: confirmAddressVerification
      description: >
        Confirm address verification by providing the transaction hash of the test transaction sent to the payout
        address.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: currency
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - txHash
              properties:
                txHash:
                  type: string
            examples:
              standard:
                summary: Typical request
                value:
                  txHash: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef'
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  txHash: txHash_example
      responses:
        '200':
          description: Address verified
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  verified:
                    type: boolean
                  verifiedAt:
                    type: string
                    format: date-time
              example:
                success: true
                message: Address verified successfully
                verified: true
                verifiedAt: '2024-01-15T10:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/projects/{projectId}/fee-balances:
    get:
      tags:
        - Project Fees
      summary: ~~Get all fee balances~~ (deprecated)
      deprecated: true
      operationId: getFeeBalances
      description: >
        Get fee balances for all currencies in a project, including collected amounts, thresholds, and payout status.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Fee balances
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        currency:
                          type: string
                        collectedAmount:
                          type: number
                        threshold:
                          type: number
                        status:
                          type: string
                        totalCollected:
                          type: number
                        totalPaidOut:
                          type: number
              example:
                success: true
                data:
                  - currency: BTC
                    collectedAmount: 0.15
                    threshold: 0.1
                    status: ready_for_payout
                    totalCollected: 0.5
                    totalPaidOut: 0.35
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/projects/{projectId}/fee-balances/{currency}:
    get:
      tags:
        - Project Fees
      summary: ~~Get currency fee balance~~ (deprecated)
      deprecated: true
      operationId: getCurrencyFeeBalance
      description: >
        Get fee balance for a specific cryptocurrency in a project.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: currency
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Currency balance
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      currency:
                        type: string
                      collectedAmount:
                        type: number
                      threshold:
                        type: number
                      status:
                        type: string
              example:
                success: true
                data:
                  currency: BTC
                  collectedAmount: 0.15
                  threshold: 0.1
                  status: ready_for_payout
                  totalCollected: 0.5
                  totalPaidOut: 0.35
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/projects/{projectId}/payout-history:
    get:
      tags:
        - Project Fees
      summary: ~~Get payout history~~ (deprecated)
      deprecated: true
      operationId: getPayoutHistory
      description: >
        Get historical payout records for a project with pagination.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: currency
          in: query
          schema:
            type: string
        - name: status
          in: query
          schema:
            type: string
            enum:
              - scheduled
              - processing
              - completed
              - failed
              - requires_attention
      responses:
        '200':
          description: Payout history
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        _id:
                          type: string
                        currency:
                          type: string
                        grossAmount:
                          type: number
                        networkFee:
                          type: number
                        netAmount:
                          type: number
                        toAddress:
                          type: string
                        txHash:
                          type: string
                        status:
                          type: string
                        createdAt:
                          type: string
                          format: date-time
                  pagination:
                    type: object
                    properties:
                      page:
                        type: integer
                      limit:
                        type: integer
                      count:
                        type: integer
                      total:
                        type: integer
                      totalPages:
                        type: integer
                      hasNextPage:
                        type: boolean
                      hasPreviousPage:
                        type: boolean
              example:
                success: true
                data:
                  - _id: 65a1b2c3d4e5f6789012345j
                    currency: BTC
                    grossAmount: 0.1
                    networkFee: 0.001
                    netAmount: 0.099
                    toAddress: bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh
                    txHash: abc123def456
                    status: completed
                    createdAt: '2024-01-15T10:00:00.000Z'
                pagination:
                  page: 1
                  limit: 20
                  count: 1
                  total: 1
                  totalPages: 1
                  hasNextPage: false
                  hasPreviousPage: false
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/projects/{projectId}/payouts/request-manual:
    post:
      tags:
        - Project Fees
      summary: ~~Request manual payout~~ (deprecated)
      deprecated: true
      operationId: requestManualPayout
      description: >
        Request a manual payout for collected fees. Requires sufficient balance above the threshold.

        Accepts: OrgBearerAuth (for admin users), ProjectBearerAuth (JWT for authenticated users), or ApiKeyAuth
        (X-API-Key for programmatic access). Both ProjectBearerAuth and ApiKeyAuth are fully implemented.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - currency
              properties:
                currency:
                  type: string
            examples:
              standard:
                summary: Typical request
                value:
                  currency: BTC
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  currency: currency_example
      responses:
        '200':
          description: Manual payout requested
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  data:
                    type: object
              example:
                success: true
                message: Manual payout requested successfully
                data:
                  payoutId: 65a1b2c3d4e5f6789012345j
                  status: queued
                  currency: BTC
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/projects/{projectId}/fee-dashboard:
    get:
      tags:
        - Project Fees
      summary: ~~Get fee dashboard~~ (deprecated)
      deprecated: true
      operationId: getProjectFeeDashboard
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Fee dashboard data
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      feeSettings:
                        type: object
                      balances:
                        type: array
                        items:
                          type: object
                          properties:
                            currency:
                              type: string
                            balance:
                              type: string
                            pending:
                              type: string
                      recentPayouts:
                        type: array
                        items:
                          type: object
                          properties:
                            _id:
                              type: string
                            amount:
                              type: string
                            currency:
                              type: string
                            status:
                              type: string
                            createdAt:
                              type: string
                              format: date-time
                      totalEarned:
                        type: number
              example:
                success: true
                data:
                  feeSettings:
                    BTC:
                      enabled: true
                      feeAmount: 0.05
                  balances:
                    - currency: BTC
                      balance: '0.5'
                      pending: '0.1'
                  recentPayouts:
                    - _id: 65a1b2c3d4e5f6789012345p
                      amount: '0.2'
                      status: completed
                      createdAt: '2024-01-15T10:00:00.000Z'
                  totalEarned: 1.5
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/projects/{projectId}/dashboard/overview:
    get:
      tags:
        - Projects
      summary: Project dashboard overview
      operationId: getProjectDashboardOverview
      description: >
        Single response for the project overview UI: project info, request counts and day-over-day % change,

        active users (distinct JWT users with project activity; realtime socket count when available),

        **Uptime** (30d headline) is organization-wide when enough HTTP samples exist, else DB heartbeat probes.
        **Average latency** (today / 7d) is **per project** and counts only routes documented in `openapi-docs.yaml` for
        customer/project API (excludes auth, `/api/users`, `/api/orgs`, role-elevation, and multi-role admin routes).
        Request volume and active users remain per-project. 14-day API call volume and recent audit activity are
        per-project.

        See docs/dashboard-overview-api.md.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            example: 65f1a2b3c4d5e6f7a8b9c0d1
      responses:
        '200':
          description: Dashboard overview
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ProjectDashboardOverviewResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/projects/{projectId}/backups:
    post:
      tags:
        - Backups
      summary: Create project backup
      operationId: createBackup
      description: >-
        Create a backup of project data, optionally including files. Supports both JWT Bearer token and API
        key authentication.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            example: 65f1a2b3c4d5e6f7a8b9c0d1
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                description:
                  type: string
                  example: Pre-deployment backup
                includeFiles:
                  type: boolean
                  default: true
                  example: true
            examples:
              standard:
                summary: Typical request
                value:
                  description: Pre-deployment backup
                  includeFiles: true
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  description: Pre-deployment backup
                  includeFiles: true
      responses:
        '201':
          description: Backup created successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  backup:
                    type: object
                    properties:
                      _id:
                        type: string
                      project:
                        type: string
                      description:
                        type: string
                      status:
                        type: string
                        enum:
                          - in_progress
                          - completed
                          - failed
                      size:
                        type: integer
                      collections:
                        type: array
                        items:
                          type: string
                      createdAt:
                        type: string
                        format: date-time
                      estimatedCompletion:
                        type: string
                        format: date-time
              example:
                message: Backup created successfully
                backup:
                  _id: bkp_abc123
                  project: 65f1a2b3c4d5e6f7a8b9c0d1
                  description: Pre-deployment backup
                  status: in_progress
                  collections: []
                  createdAt: '2024-01-15T10:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
    get:
      tags:
        - Backups
      summary: List project backups
      operationId: listBackups
      description: Get all backups for a project. Supports both JWT Bearer token and API key authentication.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: List of backups
          content:
            application/json:
              schema:
                type: object
                properties:
                  backups:
                    type: array
                    items:
                      type: object
                      properties:
                        _id:
                          type: string
                        description:
                          type: string
                        status:
                          type: string
                        size:
                          type: integer
                        collections:
                          type: array
                          items:
                            type: string
                        fileCount:
                          type: integer
                        createdAt:
                          type: string
                          format: date-time
                        completedAt:
                          type: string
                          format: date-time
                  total:
                    type: integer
              example:
                backups: []
                total: 0
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/projects/{projectId}/backups/{backupId}/restore:
    post:
      tags:
        - Backups
      summary: Restore from backup
      operationId: restoreBackup
      description: >-
        Restore project data from a backup. Supports replace or merge modes. Supports both JWT Bearer token and API key
        authentication.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: backupId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - confirmation
              properties:
                restoreMode:
                  type: string
                  enum:
                    - replace
                    - merge
                  example: replace
                collections:
                  description: 'Optional: specific collections to restore'
                  type: array
                  items:
                    type: string
                  example:
                    - products
                    - orders
                confirmation:
                  type: string
                  enum:
                    - RESTORE_DATA
                  example: RESTORE_DATA
            examples:
              standard:
                summary: Typical request
                value:
                  restoreMode: replace
                  collections:
                    - products
                    - orders
                  confirmation: RESTORE_DATA
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  restoreMode: replace
                  collections:
                    - products
                    - orders
                  confirmation: RESTORE_DATA
      responses:
        '200':
          description: Restore initiated
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Restore initiated
                  restore:
                    type: object
                    properties:
                      _id:
                        type: string
                      status:
                        type: string
                        enum:
                          - in_progress
                          - completed
                          - failed
                      restoreMode:
                        type: string
                      startedAt:
                        type: string
                        format: date-time
                      estimatedCompletion:
                        type: string
                        format: date-time
              example:
                message: Backup restored successfully
                restore:
                  _id: rst_abc123
                  status: in_progress
                  restoreMode: replace
                  startedAt: '2024-01-15T10:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/projects/{projectId}/backups/{backupId}:
    delete:
      tags:
        - Backups
      summary: Delete backup
      operationId: deleteBackup
      description: Delete a project backup. Supports both JWT Bearer token and API key authentication.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: backupId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Backup deleted successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Backup deleted successfully
              example:
                message: Backup deleted successfully
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
  /health:
    get:
      tags:
        - Health
      summary: Health check
      operationId: healthCheck
      responses:
        '200':
          description: System health status
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HealthResponse'
              example:
                status: healthy
                timestamp: '2024-01-15T10:00:00.000Z'
                services:
                  database: healthy
                  redis: healthy
                  storage: healthy
                  email: healthy
                  sms: healthy
                version: 1.0.0
                uptime: 3600
  /api/status:
    get:
      tags:
        - Health
      summary: System status
      operationId: systemStatus
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      responses:
        '200':
          description: Detailed system status
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SystemStatusResponse'
              example:
                success: true
                data:
                  uptime: 86400
                  memory:
                    used: 2147483648
                    total: 4294967296
                    percentage: 50
                  cpu:
                    usage: 12.5
                  services:
                    database: operational
                    redis: operational
                    storage: operational
                    messaging: operational
  /api/compliance/access-review:
    post:
      tags:
        - Compliance
      summary: Generate access review report (SOC 2)
      operationId: generateAccessReview
      description: >
        Generate access review report for compliance audits (SOC 2, ISO 27001, etc.).

        Requires JWT Bearer token authentication. Both OrgBearerAuth and ProjectBearerAuth are supported (they use the
        same JWT token format). These are organization-level operations.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - orgId
                - reviewPeriod
              properties:
                orgId:
                  type: string
                  example: 685acbe0e129932fbb7a0fc3
                reviewPeriod:
                  type: object
                  required:
                    - start
                    - end
                  properties:
                    start:
                      type: string
                      format: date-time
                      example: '2024-10-01T00:00:00Z'
                    end:
                      type: string
                      format: date-time
                      example: '2024-12-31T23:59:59Z'
            examples:
              standard:
                summary: Typical request
                value:
                  orgId: 685acbe0e129932fbb7a0fc3
                  reviewPeriod:
                    start: '2024-10-01T00:00:00.000Z'
                    end: '2024-12-31T23:59:59.000Z'
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  orgId: 685acbe0e129932fbb7a0fc3
                  reviewPeriod:
                    start: '2024-10-01T00:00:00.000Z'
                    end: '2024-12-31T23:59:59.000Z'
      responses:
        '200':
          description: Access review report generated
          content:
            application/json:
              schema:
                type: object
                properties:
                  report:
                    type: object
                    properties:
                      orgId:
                        type: string
                      reviewPeriod:
                        type: object
                      users:
                        type: array
                        items:
                          type: object
                      summary:
                        type: object
                      recommendations:
                        type: array
                        items:
                          type: string
                      generatedAt:
                        type: string
                        format: date-time
              example:
                success: true
                message: Access review report generated
                data:
                  orgId: 685acbe0e129932fbb7a0fc3
                  users: []
                  summary: {}
                  recommendations: []
                  generatedAt: '2024-01-15T10:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/compliance/data-processing-record:
    post:
      tags:
        - Compliance
      summary: Generate data processing record (GDPR Article 30)
      operationId: generateDataProcessingRecord
      description: Generate GDPR Article 30 compliant data processing record
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - orgId
              properties:
                orgId:
                  type: string
                  example: 685acbe0e129932fbb7a0fc3
                recordDate:
                  type: string
                  format: date-time
                  example: '2024-12-16T00:00:00Z'
            examples:
              standard:
                summary: Typical request
                value:
                  orgId: 685acbe0e129932fbb7a0fc3
                  recordDate: '2024-12-16T00:00:00.000Z'
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  orgId: 685acbe0e129932fbb7a0fc3
                  recordDate: '2024-12-16T00:00:00.000Z'
      responses:
        '200':
          description: Data processing record generated
          content:
            application/json:
              schema:
                type: object
                properties:
                  record:
                    type: object
                    properties:
                      orgId:
                        type: string
                      recordDate:
                        type: string
                        format: date-time
                      dataController:
                        type: object
                      processingActivities:
                        type: array
                        items:
                          type: object
                      dataSubjects:
                        type: array
                        items:
                          type: string
                      generatedAt:
                        type: string
                        format: date-time
              example:
                success: true
                message: Data processing record generated
                data:
                  orgId: 685acbe0e129932fbb7a0fc3
                  recordDate: '2024-12-16T00:00:00.000Z'
                  processingActivities: []
                  generatedAt: '2024-01-15T10:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/compliance/summary:
    get:
      tags:
        - Compliance
      summary: Get compliance summary
      operationId: getComplianceSummary
      description: >-
        Get compliance dashboard data (GDPR, SOC 2, security status). Requires JWT Bearer token authentication. Both
        OrgBearerAuth and ProjectBearerAuth are supported (they use the same JWT token format). These are
        organization-level operations.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      responses:
        '200':
          description: Compliance summary
          content:
            application/json:
              schema:
                type: object
                properties:
                  compliance:
                    type: object
                    properties:
                      gdpr:
                        type: object
                        properties:
                          dataExportEnabled:
                            type: boolean
                          dataErasureEnabled:
                            type: boolean
                          consentManagement:
                            type: boolean
                      soc2:
                        type: object
                        properties:
                          accessReviewsEnabled:
                            type: boolean
                          auditLoggingEnabled:
                            type: boolean
                          encryptionEnabled:
                            type: boolean
                      security:
                        type: object
                        properties:
                          passwordPolicy:
                            type: string
                          virusScanning:
                            type: boolean
                          encryptionAtRest:
                            type: boolean
              example:
                success: true
                data:
                  gdpr:
                    dataExportEnabled: true
                    dataErasureEnabled: true
                    consentManagement: true
                  soc2:
                    accessReviewsEnabled: true
                    auditLoggingEnabled: true
                    encryptionEnabled: true
                  security:
                    passwordPolicy: enabled
                    virusScanning: true
                    encryptionAtRest: true
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/compliance/security-event:
    post:
      tags:
        - Compliance
      summary: Log security event
      operationId: logSecurityEvent
      description: Log a security event for compliance and audit purposes
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - eventType
                - severity
              properties:
                eventType:
                  type: string
                  enum:
                    - unauthorized_access_attempt
                    - brute_force_attempt
                    - suspicious_api_activity
                    - private_key_export
                    - bulk_data_export
                    - admin_privilege_escalation
                    - data_breach_detected
                    - mfa_bypass_attempt
                  example: unauthorized_access_attempt
                severity:
                  type: string
                  enum:
                    - low
                    - medium
                    - high
                    - critical
                  example: high
                details:
                  type: object
                  properties:
                    userId:
                      type: string
                    resource:
                      type: string
                    ipAddress:
                      type: string
                    userAgent:
                      type: string
                    action:
                      type: string
                    reason:
                      type: string
            examples:
              standard:
                summary: Typical request
                value:
                  eventType: unauthorized_access_attempt
                  severity: high
                  details:
                    userId: 685acbe0e129932fbb7a0fc2
                    resource: admin-panel
                    ipAddress: 192.168.1.100
                    action: blocked
                    reason: Insufficient permissions
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  eventType: unauthorized_access_attempt
                  severity: high
                  details:
                    userId: userId_example
                    resource: resource_example
                    ipAddress: ipAddress_example
                    userAgent: userAgent_example
                    action: action_example
                    reason: reason_example
      responses:
        '200':
          description: Security event logged
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Security event logged
                  event:
                    type: object
                    properties:
                      _id:
                        type: string
                      eventType:
                        type: string
                      severity:
                        type: string
                      timestamp:
                        type: string
                        format: date-time
              example:
                success: true
                message: Security event recorded
                eventId: evt_abc123
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/realtime/projects/{projectId}/analytics:
    get:
      tags:
        - Real-time Analytics
      summary: Get project real-time analytics
      operationId: getProjectAnalytics
      description: Returns real-time metrics for a specific project (active connections, events, etc.)
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
            example: 65f1a2b3c4d5e6f7a8b9c0d1
      responses:
        '200':
          description: Project analytics data
          content:
            application/json:
              schema:
                type: object
                properties:
                  projectId:
                    type: string
                  activeConnections:
                    type: integer
                    example: 42
                  totalEvents:
                    type: integer
                    example: 15234
                  lastActivity:
                    type: string
                    format: date-time
                  timestamp:
                    type: string
                    format: date-time
              example:
                projectId: 65f1a2b3c4d5e6f7a8b9c0d1
                activeConnections: 42
                totalEvents: 15234
                lastActivity: '2024-01-15T10:00:00.000Z'
                timestamp: '2024-01-15T10:00:00.000Z'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/realtime/projects/{projectId}/active-users:
    get:
      tags:
        - Real-time Analytics
      summary: Get active users for a project
      operationId: getActiveUsers
      description: Returns list of currently connected users
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: List of active users
          content:
            application/json:
              schema:
                type: object
                properties:
                  users:
                    type: array
                    items:
                      type: object
                      properties:
                        userId:
                          type: string
                        connectedAt:
                          type: string
                          format: date-time
                        socketId:
                          type: string
                  count:
                    type: integer
                  timestamp:
                    type: string
                    format: date-time
              example:
                users: []
                count: 0
                timestamp: '2024-01-15T10:00:00.000Z'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/realtime/projects/{projectId}/presence:
    post:
      tags:
        - Real-time Analytics
      summary: Check presence status for users
      operationId: checkUserPresence
      description: Returns online status for specified user IDs
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - userIds
              properties:
                userIds:
                  type: array
                  items:
                    type: string
                  example:
                    - 685acbe0e129932fbb7a0fc2
                    - 685acbe0e129932fbb7a0fc3
            examples:
              standard:
                summary: Typical request
                value:
                  userIds:
                    - 685acbe0e129932fbb7a0fc2
                    - 685acbe0e129932fbb7a0fc3
              complete:
                summary: All request fields
                description: Merges the typical example with optional fields from the schema.
                value:
                  userIds:
                    - 685acbe0e129932fbb7a0fc2
                    - 685acbe0e129932fbb7a0fc3
      responses:
        '200':
          description: Presence status for each user
          content:
            application/json:
              schema:
                type: object
                properties:
                  presence:
                    type: object
                    additionalProperties:
                      type: object
                      properties:
                        online:
                          type: boolean
                        lastSeen:
                          type: string
                          format: date-time
                  timestamp:
                    type: string
                    format: date-time
              example:
                presence: {}
                timestamp: '2024-01-15T10:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/realtime/projects/{projectId}/throughput:
    get:
      tags:
        - Real-time Analytics
      summary: Get event throughput metrics
      operationId: getEventThroughput
      description: Returns event throughput for a project
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: window
          in: query
          schema:
            type: integer
            default: 60000
          description: Time window in milliseconds
      responses:
        '200':
          description: Throughput metrics
          content:
            application/json:
              schema:
                type: object
                properties:
                  windowMs:
                    type: integer
                    example: 60000
                  totalEvents:
                    type: integer
                    example: 523
                  eventsPerSecond:
                    type: number
                    example: 8.72
                  byType:
                    type: object
                    additionalProperties:
                      type: integer
                  timestamp:
                    type: string
                    format: date-time
              example:
                windowMs: 60000
                totalEvents: 523
                eventsPerSecond: 8.72
                byType: {}
                timestamp: '2024-01-15T10:00:00.000Z'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/realtime/projects/{projectId}/history:
    get:
      tags:
        - Real-time Analytics
      summary: Get historical analytics
      operationId: getHistoricalAnalytics
      description: Returns historical analytics for charting
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: period
          in: query
          schema:
            type: string
            enum:
              - hour
              - day
              - week
            default: hour
          description: Time period for historical data
      responses:
        '200':
          description: Historical analytics data
          content:
            application/json:
              schema:
                type: object
                properties:
                  projectId:
                    type: string
                  period:
                    type: string
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        timestamp:
                          type: string
                          format: date-time
                        connections:
                          type: integer
                        events:
                          type: integer
                  generatedAt:
                    type: string
                    format: date-time
              example:
                projectId: 65f1a2b3c4d5e6f7a8b9c0d1
                period: hour
                data: []
                generatedAt: '2024-01-15T10:00:00.000Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
  /api/realtime/analytics:
    get:
      tags:
        - Real-time Analytics
      summary: Get global real-time analytics
      operationId: getGlobalAnalytics
      description: Returns system-wide real-time metrics (admin only)
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
      responses:
        '200':
          description: Global analytics data
          content:
            application/json:
              schema:
                type: object
                properties:
                  activeConnections:
                    type: integer
                  peakConnections:
                    type: integer
                  totalEvents:
                    type: integer
                  eventsPerMinute:
                    type: integer
              example:
                activeConnections: 150
                peakConnections: 200
                totalEvents: 50000
                eventsPerMinute: 120
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
  /api/projects/{projectId}/analytics/email:
    get:
      tags:
        - Email
      summary: Email analytics for a project
      operationId: getProjectEmailAnalytics
      description: >
        Aggregated email log stats for the project. Optional `from` and `to` query params filter by date range (ISO
        8601).
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: from
          in: query
          required: false
          schema:
            type: string
            format: date-time
        - name: to
          in: query
          required: false
          schema:
            type: string
            format: date-time
      responses:
        '200':
          description: Analytics payload
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    additionalProperties: true
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
  /api/projects/{projectId}/email/send:
    post:
      tags:
        - Email
      summary: Enqueue project email (worker delivery)
      operationId: enqueueProjectEmail
      description: >
        Queues a transactional email for sending through the email worker and configured provider (platform or
        per-project SMTP).

        Provide either `template` (with `data`) or both `subject` and `html`. Returns **202** with `jobId` when
        accepted.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ProjectEmailSendRequest'
            examples:
              namedTemplate:
                summary: Send by template name + data
                value:
                  template: magicLink
                  to: user@example.com
                  data:
                    userName: Alex
                    magicLinkUrl: https://app.example.com/auth/verify?token=abc
                    expiresIn: 15 minutes
                  idempotencyKey: proj123:magicLink:user@example.com
              rawHtml:
                summary: Ad-hoc subject + HTML (no named template)
                value:
                  to:
                    - a@example.com
                    - b@example.com
                  subject: Order shipped
                  html: <p>Your order <strong>#1234</strong> has shipped.</p>
                  brandingScope: project
      responses:
        '202':
          description: Job accepted
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  jobId:
                    type: string
              examples:
                accepted:
                  summary: Queued
                  value:
                    success: true
                    jobId: email:65f1a2b3c4d5e6f7a8b9c0d1:01HX...
        '400':
          $ref: '#/components/responses/BadRequest'
        '503':
          description: Email queue unavailable
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: false
                  error:
                    type: string
  /api/projects/{projectId}/email/smtp:
    get:
      tags:
        - Email
      summary: Get project SMTP settings (masked)
      operationId: getProjectEmailSmtp
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: SMTP configuration without secrets
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/ProjectSmtpSettingsPublic'
    patch:
      tags:
        - Email
      summary: Update project SMTP relay (BYO)
      operationId: patchProjectEmailSmtp
      description: >
        Set `authPass` in the body to store an encrypted password (never returned on GET). Validates host/user when
        enabling.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ProjectSmtpPatchRequest'
            examples:
              enableByoSmtp:
                summary: Enable relay with new password
                value:
                  enabled: true
                  host: smtp.sendgrid.net
                  port: 587
                  secure: false
                  authUser: apikey
                  authPass: SG.xxxx
                  fromName: Acme App
                  fromEmail: noreply@mail.example.com
              disableRelay:
                summary: Turn off BYO SMTP (use platform sender)
                value:
                  enabled: false
      responses:
        '200':
          description: Updated settings (masked)
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/ProjectSmtpSettingsPublic'
              examples:
                masked:
                  summary: Saved config (password never returned)
                  value:
                    success: true
                    data:
                      enabled: true
                      host: smtp.sendgrid.net
                      port: 587
                      secure: false
                      authUser: apikey
                      hasPassword: true
                      fromName: Acme App
                      fromEmail: noreply@mail.example.com
                      domainVerifiedAt: null
        '400':
          $ref: '#/components/responses/BadRequest'
  /api/projects/{projectId}/email/smtp/test:
    post:
      tags:
        - Email
      summary: Verify SMTP and send a test message
      operationId: testProjectEmailSmtp
      description: >
        Rate-limited. With `useSaved: true` (default), uses stored credentials; otherwise pass `host`, `authUser`,
        `authPass`, etc.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ProjectSmtpTestRequest'
            examples:
              useSavedConfig:
                summary: Test using stored SMTP (default)
                value:
                  to: ops@example.com
                  useSaved: true
              adHocConnection:
                summary: One-off host/credentials (no save)
                value:
                  to: ops@example.com
                  useSaved: false
                  host: smtp.example.com
                  port: 587
                  secure: false
                  authUser: smtpuser
                  authPass: secret
                  fromEmail: alerts@example.com
                  fromName: Alerts
      responses:
        '200':
          description: SMTP verified and test mail sent
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
              examples:
                ok:
                  summary: Success
                  value:
                    success: true
                    message: SMTP verified and test message sent
        '400':
          $ref: '#/components/responses/BadRequest'
        '429':
          $ref: '#/components/responses/TooManyRequests'
  /api/projects/{projectId}/email/smtp/verify-domain:
    post:
      tags:
        - Email
      summary: Check DNS (MX + SPF) for sending domain
      operationId: verifyProjectEmailSmtpDomain
      description: >
        Resolves the domain from `domain`, `fromEmail`, or saved `emailSmtp.fromEmail`. Returns whether MX and SPF TXT
        exist.

        With `persist: true` and checks passed, sets `emailSmtp.domainVerifiedAt`.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                domain:
                  type: string
                fromEmail:
                  type: string
                persist:
                  type: boolean
                  description: If true and checks pass, persist domainVerifiedAt on the project
            examples:
              standard:
                summary: Minimal / required fields
                value:
                  domain: domain_example
                  fromEmail: fromEmail_example
                  persist: true
              complete:
                summary: All request fields
                value:
                  domain: domain_example
                  fromEmail: fromEmail_example
                  persist: true
      responses:
        '200':
          description: DNS check result
        '400':
          $ref: '#/components/responses/BadRequest'
  /api/projects/{projectId}/email/templates:
    get:
      tags:
        - Email
      summary: List email templates (full catalog for the project)
      operationId: listProjectEmailTemplates
      description: >
        Returns every template name the worker can resolve for this project: **built-in** defaults, **global** platform

        rows (`project: null` in DB), and **project** overrides. Use **`isCustomized`** to see if this project has its

        own stored copy; **`effectiveSource`** shows which layer would be used at send time (`project` wins over
        `global` over `builtin`).
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Template catalog with customization flags
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/EmailTemplateCatalogItem'
              examples:
                mixedCatalog:
                  summary: Built-in + global + one project override
                  value:
                    success: true
                    data:
                      - name: emailVerification
                        isCustomized: false
                        effectiveSource: builtin
                        subjectSnippet: Verify your email address
                        updatedAt: null
                        version: null
                      - name: magicLink
                        isCustomized: true
                        effectiveSource: project
                        subjectSnippet: Your magic link — Acme App
                        updatedAt: '2025-04-01T12:00:00.000Z'
                        version: 2
                      - name: welcome
                        isCustomized: false
                        effectiveSource: global
                        subjectSnippet: Welcome to MUDBASE
                        updatedAt: '2025-03-10T09:00:00.000Z'
                        version: 1
  /api/projects/{projectId}/email/templates/{name}:
    get:
      tags:
        - Email
      summary: Get one email template (effective content)
      operationId: getProjectEmailTemplate
      description: >
        Returns the template body that would be used when sending: project override if present, else global default,

        else built-in fallback. **`isProjectOverride`** is true only when this project has a stored row;
        **`effectiveSource`**

        is `project`, `global`, or `builtin`.
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: name
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Template document (resolved for send)
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/EmailTemplateResolved'
              examples:
                projectOverride:
                  summary: Project-customized template
                  value:
                    success: true
                    data:
                      name: magicLink
                      subject: Sign in to {{projectName}}
                      htmlBody: <h1>Sign in</h1><p><a href="{{magicLinkUrl}}">Continue</a></p>
                      textBody: ''
                      variables:
                        - userName
                        - magicLinkUrl
                        - projectName
                        - expiresIn
                      updatedAt: '2025-04-01T12:00:00.000Z'
                      version: 2
                      isProjectOverride: true
                      effectiveSource: project
                builtinFallback:
                  summary: Built-in default (no DB row for project)
                  value:
                    success: true
                    data:
                      name: emailVerification
                      subject: Verify your email address
                      htmlBody: >-
                        <h1>Verify your email</h1><p>Hi {{userName}},</p><p><a href="{{verificationUrl}}">Verify
                        Email</a></p>
                      textBody: ''
                      variables: []
                      updatedAt: null
                      version: null
                      isProjectOverride: false
                      effectiveSource: builtin
        '404':
          $ref: '#/components/responses/NotFound'
    put:
      tags:
        - Email
      summary: Upsert project email template (HTML sanitized; variables must cover {{placeholders}})
      operationId: upsertProjectEmailTemplate
      description: >
        Saves a **project override** for `name`. HTML is sanitized. **`variables`** must list every `{{token}}` used in
        `subject`, `htmlBody`, and `textBody` (see **Email** tag description for the full placeholder catalog).
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: name
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - subject
                - htmlBody
              properties:
                subject:
                  type: string
                htmlBody:
                  type: string
                textBody:
                  type: string
                variables:
                  type: array
                  items:
                    type: string
            examples:
              standard:
                summary: Minimal / required fields
                value:
                  subject: subject_example
                  htmlBody: htmlBody_example
              complete:
                summary: All request fields
                value:
                  subject: subject_example
                  htmlBody: htmlBody_example
                  textBody: textBody_example
                  variables:
                    - example_item
      responses:
        '200':
          description: Saved template
        '400':
          $ref: '#/components/responses/BadRequest'
  /api/projects/{projectId}/email/templates/{name}/preview:
    post:
      tags:
        - Email
      summary: Render template preview (sanitized HTML, no send)
      operationId: previewProjectEmailTemplate
      description: >
        Body **`sampleData`** is merged with layout defaults; keys should match `{{placeholders}}` in the template (see
        **Email** tag for the catalog).
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: name
          in: path
          required: true
          schema:
            type: string
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                sampleData:
                  type: object
                  additionalProperties: true
            examples:
              standard:
                summary: Minimal / required fields
                value:
                  sampleData: {}
              complete:
                summary: All request fields
                value:
                  sampleData: {}
      responses:
        '200':
          description: Rendered subject and HTML
  /api/projects/{projectId}/email/templates/{name}/restore-default:
    post:
      tags:
        - Email
      summary: Restore from platform global default or remove project override
      operationId: restoreDefaultProjectEmailTemplate
      security:
        - OrgBearerAuth: []
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema:
            type: string
        - name: name
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Restored or deleted override
  /api/gdpr/export:
    get:
      summary: Export my personal data (GDPR Art. 15)
      description: >-
        Returns the authenticated subject's personal data as a downloadable JSON attachment. Self-scoped — a caller can
        only export their own data.
      tags:
        - Compliance
      security:
        - OrgBearerAuth: []
      responses:
        '200':
          description: JSON attachment containing the subject's personal data
          content:
            application/json:
              schema:
                type: object
        '401':
          description: Authentication required
        '429':
          description: Rate limit exceeded
  /api/gdpr/erase:
    post:
      summary: Erase my personal data (GDPR Art. 17)
      description: |
        Anonymizes the subject's PII, revokes sessions/tokens, and anonymizes (never hard-deletes)
        financial/legal-retention records. Idempotent and self-scoped.

        Requires re-proving your current password (skipped only for OAuth-only accounts with no
        password set) and, if 2FA is enabled, a fresh TOTP code - the same step-up re-authentication
        already required by the less-destructive `PATCH /api/users/password` and
        `POST /api/users/2fa/disable`.
      tags:
        - Compliance
      security:
        - OrgBearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - confirm
              properties:
                confirm:
                  type: string
                  enum:
                    - DELETE
                  description: Must equal "DELETE" to proceed with erasure.
                currentPassword:
                  type: string
                  description: Required unless the account has no password set (OAuth-only)
                  example: CurrentPassword123!
                totpToken:
                  type: string
                  description: Required only if the account has 2FA enabled
                  example: '123456'
      responses:
        '200':
          description: Data anonymized (or already anonymized — idempotent)
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  data:
                    type: object
        '400':
          description: Confirmation field missing/not equal to "DELETE", or currentPassword/totpToken missing or invalid
        '401':
          description: Authentication required
        '409':
          description: Sole owner of one or more organizations - transfer or delete them first
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                  soleOwnedOrgs:
                    type: array
                    items:
                      type: string
        '429':
          description: Rate limit exceeded
  /api/me/bootstrap:
    get:
      summary: Dashboard bootstrap (session + orgs + default org + projects)
      description: >-
        Consolidated dashboard warmup in a single round-trip. Returns the session user, the user's organizations, the
        resolved default organization, and that org's projects. Shapes match GET /api/auth/session, GET /api/orgs and
        GET /api/projects.
      tags:
        - Users
      security:
        - OrgBearerAuth: []
      responses:
        '200':
          description: Bootstrap payload
          content:
            application/json:
              schema:
                type: object
                properties:
                  user:
                    type: object
                  organizations:
                    type: array
                    items:
                      type: object
                  defaultOrg:
                    type: object
                    nullable: true
                  projects:
                    type: array
                    items:
                      type: object
        '401':
          description: Authentication required
        '500':
          description: Failed to load bootstrap data
  /api/addons:
    get:
      summary: List the add-on catalog
      description: Returns the available add-ons (key, metadata, pricing) the caller can invoke.
      tags:
        - Add-ons
      security:
        - OrgBearerAuth: []
      responses:
        '200':
          description: Add-on catalog
          content:
            application/json:
              schema:
                type: object
                properties:
                  addons:
                    type: array
                    items:
                      type: object
        '401':
          description: Authentication required
  /api/projects/{projectId}/addons/{addon}/invoke:
    post:
      summary: Invoke an add-on for a project
      description: >-
        Runs the named add-on against the project. Returns the job synchronously (200) when it completes immediately, or
        202 with a pending job when processing continues in the background.
      tags:
        - Add-ons
      security:
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - in: path
          name: projectId
          required: true
          schema:
            type: string
        - in: path
          name: addon
          required: true
          schema:
            type: string
          description: Add-on key from the catalog.
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              description: Add-on-specific input payload.
      responses:
        '200':
          description: Add-on job completed
          content:
            application/json:
              schema:
                type: object
                properties:
                  job:
                    type: object
        '202':
          description: Add-on job accepted and processing
          content:
            application/json:
              schema:
                type: object
                properties:
                  job:
                    type: object
        '400':
          description: Invalid add-on key or input
        '401':
          description: Authentication required
        '403':
          description: Project ownership required
  /api/projects/{projectId}/addons/jobs/{id}:
    get:
      summary: Get an add-on job status
      tags:
        - Add-ons
      security:
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - in: path
          name: projectId
          required: true
          schema:
            type: string
        - in: path
          name: id
          required: true
          schema:
            type: string
          description: Add-on job id.
      responses:
        '200':
          description: The add-on job
          content:
            application/json:
              schema:
                type: object
                properties:
                  job:
                    type: object
        '401':
          description: Authentication required
        '403':
          description: Project ownership required
        '404':
          description: Add-on job not found
  /api/files/download/{fileId}:
    get:
      summary: Get a download URL for a file
      description: >-
        Returns a URL to download the file. For private files a short-lived signed URL is generated; the lifetime can be
        tuned per request via the optional expiresIn query parameter (seconds, clamped to a safe server-configured
        range). For public (public-read) files the permanent world-readable URL is returned with isPublic true and a
        warning, since signing a public object provides no protection. Accepts a JWT (Bearer) or a project API key.
      tags:
        - Files
      security:
        - ProjectBearerAuth: []
        - ApiKeyAuth: []
      parameters:
        - in: path
          name: fileId
          required: true
          schema:
            type: string
        - in: query
          name: expiresIn
          required: false
          schema:
            type: integer
            minimum: 1
          description: >-
            Signed-URL lifetime in seconds for private files. Clamped to the server's min/max range; ignored for public
            files. Defaults to the server's configured expiry.
      responses:
        '200':
          description: Download URL (signed for private files, permanent for public files)
          content:
            application/json:
              schema:
                type: object
                properties:
                  url:
                    type: string
                  expiresIn:
                    type: integer
                    nullable: true
                    description: Seconds until the signed URL expires; null for public files.
                  isPublic:
                    type: boolean
                    description: Present and true only when the file is public.
                  warning:
                    type: string
                    description: Present only for public files — explains the URL is permanent and unprotected.
        '403':
          description: Access denied or download limit exceeded
        '404':
          description: File not found
        '500':
          description: Failed to generate download URL
  /mcp/config:
    get:
      summary: MCP connection status for the current org
      description: >-
        Whether the org's plan includes MCP access and, when enabled, the endpoint URL an MCP client should connect to
        (the org's dedicated API host if it has dedicated infrastructure, otherwise the shared platform host). Auth here
        is the normal dashboard session - this powers the console's MCP settings page, distinct from the
        API-key-authenticated POST / endpoint an actual MCP client calls.
      tags:
        - MCP
      security:
        - OrgBearerAuth: []
      responses:
        '200':
          description: MCP status for the current org
          content:
            application/json:
              schema:
                type: object
                properties:
                  enabled:
                    type: boolean
                  plan:
                    type: string
                  allowedPlans:
                    type: array
                    items:
                      type: string
                  freePromoActive:
                    type: boolean
                    description: True if this org is on the free plan and MCP is temporarily enabled via the launch promo
                  freePromoEndsAt:
                    type: string
                    format: date-time
                    nullable: true
                    description: When the free-plan MCP promo ends (null if not active)
                  endpoint:
                    type: string
                  tools:
                    type: array
                    items:
                      type: object
                      properties:
                        name:
                          type: string
                        description:
                          type: string
        '401':
          description: Authentication required
  /api/files/public/{fileId}:
    get:
      summary: Redirect to a public file's content
      description: >-
        Unauthenticated. Only serves files with isPublic=true whose upload has been confirmed and whose virus scan came
        back clean - the object storage backend has no per-object ACL, so this route (not the storage bucket) is what actually
        decides whether a "public" file's bytes are reachable. 302-redirects to a fresh, short-lived (60s) signed GET
        url so the actual bytes are still served straight off the storage edge.
      tags:
        - Files
      parameters:
        - in: path
          name: fileId
          required: true
          schema:
            type: string
      responses:
        '302':
          description: Redirect to a short-lived signed download URL
        '403':
          description: File is not public
        '404':
          description: File not found, or not yet confirmed/scanned
  /api/files/logo-redirect:
    get:
      summary: Redirect to an org/project logo's content
      description: >-
        Unauthenticated. Logos are always meant to be public branding assets, but the object storage backend has no per-object ACL,
        so this route (not the bucket) is what actually serves them - the `key` query param is validated against the
        exact shape logoStorageService.uploadLogo() produces before signing, so this can never be used to fetch an
        arbitrary storage key. 302-redirects to a short-lived signed GET url.
      tags:
        - Files
      parameters:
        - in: query
          name: key
          required: true
          schema:
            type: string
      responses:
        '302':
          description: Redirect to a short-lived signed download URL
        '400':
          description: Key does not match the expected logo key shape
components:
  securitySchemes:
    OrgBearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: |
        JWT Bearer token obtained from authentication endpoints (/api/auth/login, /api/auth/register, etc.).
        This is the same JWT token format as ProjectBearerAuth - the distinction is contextual (where it's used).

        **How it works**:
        - Provide JWT token in Authorization: Bearer <token> header
        - Token contains user ID and organization context
        - Used for organization-level operations (org management, user management, billing, etc.)
        - Also works for project-scoped operations (same token, different context)

        **Note**: OrgBearerAuth and ProjectBearerAuth use the same JWT token format. The difference is semantic - 
        OrgBearerAuth is listed for organization/user management endpoints, while ProjectBearerAuth is listed 
        for project-scoped endpoints. Both work for any endpoint that uses `authRequired` middleware.
    ProjectBearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: >
        JWT Bearer token for project-scoped operations. **This is the same JWT token format as OrgBearerAuth** - 

        the distinction is contextual (where it's used). Can be used instead of or alongside ApiKeyAuth for project
        operations.


        **Implementation Status**: ✅ Fully implemented in all project-scoped endpoints.


        **How it works**:

        - Provide JWT token in Authorization: Bearer <token> header

        - Token is obtained from authentication endpoints (/api/auth/login, /api/auth/register, etc.)

        - Token contains user ID and organization context

        - Project access is validated to ensure project belongs to user's organization


        **When to use**:

        - User-facing applications

        - When you need user identity and context

        - When you want role-based access control (RBAC)

        - When you need audit trails with user information


        **Important**: OrgBearerAuth and ProjectBearerAuth are the same JWT token format. Any endpoint that accepts 

        JWT tokens (via `authRequired` middleware) will accept both. The distinction in the OpenAPI spec is semantic 

        to indicate the primary context of use.


        **Note**: If both Authorization Bearer token and X-API-Key are provided, JWT authentication is tried first.
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key
      description: |
        Project-level API key for programmatic access.
        Used for server-to-server integrations and SDK-based access.
        Can be used instead of or alongside ProjectBearerAuth (JWT token).

        **Implementation Status**: ✅ Fully implemented in all project-scoped endpoints.

        **How it works**:
        - Provide API key in X-API-Key header
        - API key must be active and not expired
        - API key must have appropriate permissions for the resource/action
        - API key is rate-limited per key configuration

        **When to use**:
        - Server-to-server integrations
        - SDK-based access
        - Automated scripts and background jobs
        - Programmatic API access without user context

        **Permissions**: API keys can have permissions for:
        - `database` - Data and collection operations
        - `storage` - File and bucket operations
        - `functions` - Function execution
        - `auth` - Authentication operations
        - `realtime` - Real-time operations

        **Rate Limiting**: Each API key has configurable rate limits (default: 1000 requests/hour).

        **Obtain from**: Create via POST /api/api-keys endpoint (requires JWT authentication).

        **Note**: If both Authorization Bearer token and X-API-Key are provided, JWT authentication is tried first.
    InternalApiKey:
      type: apiKey
      in: header
      name: X-Internal-Api-Key
      description: |
        Platform internal operations (enterprise provisioning, DNS batch recheck, custom-domain add-on).
        Set `INTERNAL_API_KEY` in the API environment; omit from public SDKs.
  schemas:
    AppRoleFeaturePermissions:
      type: object
      description: >
        App JWT feature toggles stored on `MultiRoleFeature.roles[].featurePermissions`.

        Structure: `{ [resource: string]: { [action: string]: boolean } }`. Only **explicit `false`**

        on a key that matches the resolved gate denies; missing resources/actions imply no extra denial.


        **Canonical map** of `(resource, action)` pairs enforced at runtime: `services/appRoleFeatureMap.js`

        (`RULES`). Regenerate inventory: `node scripts/verify-app-role-feature-map.js`.


        **Messaging** also accepts legacy keys (`email`, `sms`, `push`, `history`, `stats`) alongside

        `send_email`, `send_sms`, `send_push`, `read_history`, `read_stats` — see `services/appRoleFeatureService.js`
        (`MESSAGING_SYNONYMS`).


        | Resource | Actions (boolean keys under the resource object) |

        |----------|--------------------------------------------------|

        | `messaging` | `send_email`, `send_sms`, `send_push`, `read_history`, `read_stats` (legacy: `email`, `sms`,
        `push`, `history`, `stats`) |

        | `integration` | `read`, `create`, `update`, `delete`, `execute`, `test`, `export`, `read_usage` |

        | `functions` | `create`, `read`, `update`, `delete`, `execute`, `simulate` |

        | `data` | `create`, `read`, `update`, `delete` |

        | `search` | `query`, `suggestions`, `read_analytics` |

        | `usage` | `read` |

        | `storage` | `read`, `create`, `update`, `delete`, `upload` |

        | `chat` | `read`, `create`, `update`, `delete` |

        | `realtime` | `read_analytics`, `read_active_users`, `presence`, `read_throughput`, `read_history` |

        | `roleElevation` | `request`, `status`, `documents` |

        | `webhooks` | `config_read`, `config_update`, `test_transformation` |
      additionalProperties:
        type: object
        additionalProperties:
          type: boolean
      example:
        messaging:
          email: true
          sms: true
          push: false
          history: true
          stats: true
        integration:
          read: true
          execute: true
        storage:
          read: true
          upload: true
    AdminOrgLimitsPatchRequest:
      description: |
        Partial org limit overrides for platform admins. At least one property required.
        Keys match `PLANS[*].limits` in the backend; integers are non-negative or null for unlimited.
      type: object
      minProperties: 1
      properties:
        projects:
          type: integer
          minimum: 0
          nullable: true
        storage:
          type: integer
          minimum: 0
          nullable: true
        bandwidth:
          type: integer
          minimum: 0
          nullable: true
        apiCalls:
          type: integer
          minimum: 0
          nullable: true
        buckets:
          type: integer
          minimum: 0
          nullable: true
        collections:
          type: integer
          minimum: 0
          nullable: true
        realtimeConnections:
          type: integer
          minimum: 0
          nullable: true
        realtimeMessages:
          type: integer
          minimum: 0
          nullable: true
        chatMessagesPerMonth:
          type: integer
          minimum: 0
          nullable: true
        apiKeysPerProject:
          type: integer
          minimum: 0
          nullable: true
        webhooksPerProject:
          type: integer
          minimum: 0
          nullable: true
        functionsPerProject:
          type: integer
          minimum: 0
          nullable: true
        functionInvocationsPerMonth:
          type: integer
          minimum: 0
          nullable: true
        messagingMessagesPerMonth:
          type: integer
          minimum: 0
          nullable: true
        smsPerMonth:
          type: integer
          minimum: 0
          nullable: true
        chatChannelsPerProject:
          type: integer
          minimum: 0
          nullable: true
        backupsPerProject:
          type: integer
          minimum: 0
          nullable: true
        restoresPerMonth:
          type: integer
          minimum: 0
          nullable: true
        integrationsPerProject:
          type: integer
          minimum: 0
          nullable: true
        rolesPerOrg:
          type: integer
          minimum: 0
          nullable: true
        alertsPerProject:
          type: integer
          minimum: 0
          nullable: true
        blockchainChains:
          type: integer
          minimum: 0
          nullable: true
        teamUsers:
          type: integer
          minimum: 0
          nullable: true
        bugAnalysis:
          type: object
          properties:
            scansPerMonth:
              type: integer
              minimum: 0
              nullable: true
            maxUploadBytes:
              type: integer
              minimum: 0
              nullable: true
            maxRuntimeMinutes:
              type: integer
              minimum: 0
              nullable: true
            queueType:
              type: string
              enum:
                - none
                - standard
                - priority
                - dedicated
            logRetentionDays:
              type: integer
              minimum: 0
              nullable: true
    AdminOrgPlanPatchRequest:
      type: object
      required:
        - plan
      properties:
        plan:
          type: string
          enum:
            - free
            - basic
            - starter
            - growth
            - scale
            - enterprise
        reason:
          type: string
        txPlan:
          type: string
          nullable: true
          enum:
            - starter
            - growth
            - scale
            - enterprise
    AdminOrgStatusPatchRequest:
      type: object
      required:
        - isActive
      properties:
        isActive:
          type: boolean
        platformSuspendedReason:
          type: string
          nullable: true
        platformAdminNote:
          type: string
          nullable: true
        reason:
          type: string
    AdminOrgBillingContractPatchRequest:
      type: object
      description: At least one contract field required (excluding reason alone).
      properties:
        contractAmountCents:
          type: integer
          minimum: 0
          nullable: true
        contractCurrency:
          type: string
          nullable: true
        contractBillingInterval:
          type: string
          enum:
            - monthly
            - yearly
          nullable: true
        contractEffectiveFrom:
          type: string
          format: date-time
          nullable: true
        contractNotes:
          type: string
          nullable: true
        reason:
          type: string
    AdminProvisionEnterpriseBody:
      type: object
      required:
        - provisionRequestId
        - apiBaseUrl
        - dbRef
        - serverId
      properties:
        provisionRequestId:
          type: string
        apiBaseUrl:
          type: string
        dbRef:
          type: string
        serverId:
          type: string
        region:
          type: string
          nullable: true
        version:
          type: string
          nullable: true
        forceOverride:
          type: boolean
    AdminProjectPatchRequest:
      type: object
      minProperties: 1
      properties:
        name:
          type: string
          minLength: 1
          maxLength: 100
        slug:
          type: string
          minLength: 2
          maxLength: 50
          pattern: ^[a-z0-9-]+$
        isArchived:
          type: boolean
    AdminMemberRolePatchRequest:
      type: object
      required:
        - role
      properties:
        role:
          type: string
          enum:
            - owner
            - admin
            - developer
            - viewer
        reason:
          type: string
    AdminBillingCheckoutLinkRequest:
      type: object
      required:
        - plan
      properties:
        plan:
          type: string
          enum:
            - starter
            - growth
            - scale
            - enterprise
        billingCycle:
          type: string
          enum:
            - monthly
            - yearly
          default: monthly
        amountCents:
          type: integer
          minimum: 1
          description: Monthly amount in cents (overrides catalog; enterprise default is contract)
        chargeAmountCents:
          type: integer
          minimum: 1
          description: Exact charge in cents for this checkout (overrides monthly math)
        currency:
          type: string
        email:
          type: string
          format: email
        name:
          type: string
        redirectUrl:
          type: string
          format: uri
        sendEmail:
          type: boolean
          default: false
        toEmail:
          type: string
          format: email
        message:
          type: string
          description: Optional note shown in org_billing_checkout email
    RegisterRequest:
      type: object
      required:
        - email
        - password
        - firstName
        - lastName
        - agreedToTerms
      properties:
        email:
          type: string
          format: email
          example: john.doe@mudbase.dev
        password:
          type: string
          minLength: 8
          example: SecurePass123!
        firstName:
          type: string
          example: John
        lastName:
          type: string
          example: Doe
        orgName:
          type: string
          example: Mudbase
        agreedToTerms:
          type: boolean
          description: >-
            Must be `true` - the server rejects the request otherwise. Required to stop a direct API call from
            creating an account without accepting the Terms of Service and Privacy Policy.
          enum:
            - true
        captcha:
          type: string
          description: >-
            Google reCAPTCHA v3 response token, required only when the platform's anti-bot CAPTCHA gate is enabled.
            A missing token then gets a 400 with `captchaRequired: true` and a `siteKey`. Solving this needs a real
            browser, so this endpoint backs the web console's own signup form
            (`https://www.mudbase.dev/console/register`) and is not meant for scripted/server-to-server account
            creation. To integrate: create your Mudbase account once through the console, then use the API key from
            Settings -> API Keys for everything else - collections, documents, storage, and the rest of the API are
            all fully scriptable from there.
    LoginRequest:
      type: object
      required:
        - email
        - password
      properties:
        email:
          type: string
          format: email
          example: john.doe@mudbase.dev
        password:
          type: string
          example: SecurePass123!
    AuthResponse:
      type: object
      properties:
        message:
          type: string
        token:
          type: string
          description: JWT access token (use in Authorization Bearer header)
        refreshToken:
          type: string
          description: JWT refresh token (use with POST /api/auth/refresh to get new token pair)
        expiresIn:
          type: integer
          description: Access token TTL in seconds (e.g. 1800 for 30 minutes)
        user:
          $ref: '#/components/schemas/User'
    SessionResponse:
      type: object
      properties:
        user:
          $ref: '#/components/schemas/User'
        authenticated:
          type: boolean
    MagicLinkRequest:
      type: object
      required:
        - email
        - projectId
      properties:
        email:
          type: string
          format: email
        projectId:
          type: string
        redirectUrl:
          type: string
    OTPSendRequest:
      type: object
      required:
        - projectId
        - method
      properties:
        phone:
          type: string
        email:
          type: string
          format: email
        projectId:
          type: string
        method:
          type: string
          enum:
            - sms
            - email
    OTPVerifyRequest:
      type: object
      required:
        - projectId
        - otp
      properties:
        identifier:
          type: string
        otp:
          type: string
        projectId:
          type: string
    User:
      type: object
      properties:
        _id:
          type: string
        email:
          type: string
          format: email
        firstName:
          type: string
        lastName:
          type: string
        fullName:
          type: string
        avatar:
          type: string
        role:
          type: string
          enum:
            - owner
            - admin
            - member
            - viewer
        customRole:
          type: string
          nullable: true
          description: >-
            Application-level role slug from the project's Multi-Role feature (e.g. "customer", "seller"). Null for
            org-level (org/admin/member/viewer) users who aren't project end-users.
        isAnonymous:
          type: boolean
          description: >-
            True for a guest session created via POST /api/auth/anonymous that hasn't been converted to a full account
            yet.
        emailVerified:
          type: boolean
        phoneVerified:
          type: boolean
        twoFactorEnabled:
          type: boolean
        lastLogin:
          type: string
          format: date-time
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
        org:
          $ref: '#/components/schemas/OrganizationSummary'
    UpdateUserRequest:
      type: object
      properties:
        firstName:
          type: string
        lastName:
          type: string
        avatar:
          type: string
    ChangePasswordRequest:
      type: object
      required:
        - currentPassword
        - newPassword
      properties:
        currentPassword:
          type: string
        newPassword:
          type: string
          minLength: 8
    TwoFASetupResponse:
      type: object
      properties:
        secret:
          type: string
        qrCode:
          type: string
        manualEntryKey:
          type: string
    Organization:
      type: object
      properties:
        _id:
          type: string
        name:
          type: string
        slug:
          type: string
        description:
          type: string
        logo:
          type: string
          format: uri
          description: >-
            Optional logo URL. Org-related emails use the platform logo (env); this field is for legacy or future UI use
            only.
        website:
          type: string
        plan:
          $ref: '#/components/schemas/Plan'
        usage:
          $ref: '#/components/schemas/Usage'
        limits:
          $ref: '#/components/schemas/Limits'
        billing:
          $ref: '#/components/schemas/Billing'
        settings:
          type: object
          description: >-
            May include customDomainAddon (optional billing/legacy flag; not required for custom domains on
            Growth/Scale).
        deploymentType:
          type: string
          enum:
            - shared
            - dedicated
        dedicated:
          type: object
          description: Dedicated API/DB routing; may include edgeTlsStatus, infraMeteringLastReportAt.
        preferredRegion:
          type: string
          nullable: true
        infrastructureEnvironments:
          type: array
          items:
            type: object
        allowedDomains:
          type: array
          items:
            type: object
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    OrganizationSummary:
      type: object
      properties:
        _id:
          type: string
        name:
          type: string
        slug:
          type: string
    UpdateOrganizationRequest:
      type: object
      properties:
        name:
          type: string
        description:
          type: string
        logo:
          type: string
          format: uri
          description: Optional logo URL. Not used for emails (org emails use platform logo).
        website:
          type: string
        settings:
          type: object
    AddOrgDomainRequest:
      type: object
      required:
        - hostname
      properties:
        hostname:
          type: string
        setPrimary:
          type: boolean
    OrgSslValidationRecord:
      type: object
      properties:
        txtName:
          type: string
          nullable: true
        txtValue:
          type: string
          nullable: true
        httpUrl:
          type: string
          nullable: true
        httpBody:
          type: string
          nullable: true
        cname:
          type: string
          nullable: true
        cnameTarget:
          type: string
          nullable: true
    OrgEdgeHints:
      type: object
      description: Managed edge TLS custom-hostname hints returned after Mudbase verification (when the edge TLS integration is configured)
      properties:
        saasIntegrationEnabled:
          type: boolean
        skipped:
          type: boolean
        reason:
          type: string
          nullable: true
        customHostnameId:
          type: string
          nullable: true
        hostnameStatus:
          type: string
          nullable: true
        sslStatus:
          type: string
          nullable: true
        ownershipVerification:
          type: object
          nullable: true
          properties:
            name:
              type: string
            type:
              type: string
            value:
              type: string
        sslValidationRecords:
          type: array
          items:
            $ref: '#/components/schemas/OrgSslValidationRecord'
        lastError:
          type: string
          nullable: true
        instructions:
          type: string
          nullable: true
    OrgDomainEntryWithDns:
      type: object
      description: >-
        Full allowed-domain row (admin and legacy): includes **`dnsTxtHost`** / **`dnsTxtValue`**, optional managed edge
        TLS hints, staff-published step-3 TXT (`platformDnsVerification` on the manual path), and
        unified **`dnsRecords`** when the API builds a checklist. **`routingCnameTarget`** is the managed routing CNAME
        target when the certificate has provisioned, else the platform default. Org-facing routes return the compact
        **`OrgDomainEntryOrgConsole`** shape instead (no raw `verificationToken` or duplicate TXT keys).
      properties:
        _id:
          type: string
          description: Subdocument id when present (MongoDB)
        hostname:
          type: string
        hostnameNormalized:
          type: string
          nullable: true
        status:
          type: string
        isPrimary:
          type: boolean
        source:
          type: string
          enum:
            - manual
            - api
            - imported
        verificationToken:
          type: string
        createdAt:
          type: string
          format: date-time
        verifiedAt:
          type: string
          format: date-time
          nullable: true
        lastVerifiedAt:
          type: string
          format: date-time
          nullable: true
        dnsTxtHost:
          type: string
          description: FQDN for the TXT record (e.g. _mudbase-verify.example.com)
        dnsTxtValue:
          type: string
          description: Exact TXT string value (mudbase-domain-verification=<token>)
        edge:
          $ref: '#/components/schemas/OrgEdgeHints'
        platformActivationPending:
          type: boolean
          description: True while Mudbase TXT passed but custom host not yet active (includes CNAME and platform DNS pipeline).
        customDomainLiveForApiTraffic:
          type: boolean
        customDomainVerificationStep:
          type: integer
          nullable: true
          description: Console wizard step 1–3; null when active/verified.
        routingCnameTarget:
          type: string
          nullable: true
          description: >-
            Routing CNAME target: the managed certificate's provisioned CNAME target when requirements have been stored;
            otherwise the platform default target.
        dnsRecords:
          type: array
          description: >-
            Unified checklist: Mudbase ownership TXT, routing CNAME (purpose `routing`) when provisioned else the
            platform default, and the managed certificate-provisioning rows once the managed
            certificate has been provisioned after the Mudbase TXT. Empty or absent when the certificate is not yet
            provisioned. Prefer this over `platformDnsVerification` alone for org-facing DNS UI.
          items:
            $ref: '#/components/schemas/OrgDnsRecord'
        flyCertificateStatus:
          type: string
          nullable: true
          description: >-
            Managed certificate `status` during provisioning (e.g. `pending_validation`, `active`). Null when managed
            certificate provisioning is not in use for this deployment.
        platformDnsVerification:
          $ref: '#/components/schemas/OrgPlatformDnsVerificationCustomer'
        cnameSubmittedAt:
          type: string
          format: date-time
          nullable: true
        cnameApprovedAt:
          type: string
          format: date-time
          nullable: true
        platformDnsVerificationSubmittedAt:
          type: string
          format: date-time
          nullable: true
    OrgDomainEntryOrgConsole:
      type: object
      description: >-
        Org API compact domain row: use **`dnsRecords`** for the Mudbase ownership TXT (purpose `mudbase_ownership`) and
        routing CNAME. Omits `hostnameNormalized`, `verificationToken`, `dnsTxtHost`, and `dnsTxtValue`. Omits
        `edge` when edge SSL is not configured. Optional keys with no value are omitted from JSON
        responses.
      properties:
        _id:
          type: string
        hostname:
          type: string
        status:
          type: string
        isPrimary:
          type: boolean
        source:
          type: string
          enum:
            - manual
            - api
            - imported
        createdAt:
          type: string
          format: date-time
        verifiedAt:
          type: string
          format: date-time
          nullable: true
        lastVerifiedAt:
          type: string
          format: date-time
          nullable: true
        cnameSubmittedAt:
          type: string
          format: date-time
          nullable: true
        cnameApprovedAt:
          type: string
          format: date-time
          nullable: true
        customDomainVerificationStep:
          type: integer
          nullable: true
        routingCnameTarget:
          type: string
          nullable: true
        dnsRecords:
          type: array
          items:
            $ref: '#/components/schemas/OrgDnsRecord'
        platformActivationPending:
          type: boolean
        customDomainLiveForApiTraffic:
          type: boolean
        edge:
          $ref: '#/components/schemas/OrgEdgeHints'
        flyCertificateStatus:
          type: string
          nullable: true
        platformDnsVerification:
          $ref: '#/components/schemas/OrgPlatformDnsVerificationCustomer'
        platformDnsVerificationSubmittedAt:
          type: string
          format: date-time
          nullable: true
    OrgDnsRecord:
      type: object
      properties:
        type:
          type: string
          description: DNS record type (TXT, CNAME, …)
        name:
          type: string
          description: Owner name / FQDN to create at the customer's DNS host
        value:
          type: string
          description: Record value or CNAME target
        purpose:
          type: string
          description: mudbase_ownership, routing, fly_ownership, acme_challenge, or fly (legacy bucket).
      required:
        - type
        - name
        - value
        - purpose
    OrgPlatformDnsVerificationCustomer:
      type: object
      nullable: true
      description: >-
        Additional DNS record from platform staff (manual path), or the first certificate-provisioning TXT shim when
        automated provisioning is enabled. Prefer `dnsRecords` for full instructions. `staffNote` may appear in admin
        org detail only.
      properties:
        recordType:
          type: string
        recordName:
          type: string
        recordValue:
          type: string
        ttlSeconds:
          type: integer
          nullable: true
        staffNote:
          type: string
          nullable: true
        updatedAt:
          type: string
          format: date-time
          nullable: true
    AdminApproveOrgDomainCnameRequest:
      type: object
      properties:
        verifyDns:
          type: boolean
          description: >-
            When true, public DNS CNAME chain for hostname must match Fly `dns_requirements.cname` when stored, else
            `CUSTOM_DOMAIN_API_CNAME_TARGET`.
    AdminPlatformDnsVerificationPatchRequest:
      type: object
      required:
        - recordName
        - recordValue
      properties:
        recordType:
          type: string
          maxLength: 32
        recordName:
          type: string
          maxLength: 512
        recordValue:
          type: string
          maxLength: 4096
        ttlSeconds:
          type: integer
          minimum: 0
          maximum: 86400
          nullable: true
        staffNote:
          type: string
          maxLength: 4000
          nullable: true
        resetCustomerPlatformDnsSubmission:
          type: boolean
        notifyOrg:
          type: boolean
          description: When not false (default), email org billing contact with step-3 DNS instructions after save.
    AdminCustomDomainMutationResponse:
      type: object
      required:
        - success
        - domain
      properties:
        success:
          type: boolean
        domain:
          $ref: '#/components/schemas/OrgDomainEntryWithDns'
    OrgAddDomainResponse:
      type: object
      required:
        - success
        - domain
      properties:
        success:
          type: boolean
        domain:
          $ref: '#/components/schemas/OrgDomainEntryOrgConsole'
        dnsVerificationInstructions:
          type: string
          description: >-
            Plain-language reminder to add the ownership TXT from the domain’s DNS checklist, then use Verify DNS in the
            organization’s domain settings.
    OrgDnsInstructionsResponse:
      type: object
      required:
        - success
        - domain
      properties:
        success:
          type: boolean
        domain:
          $ref: '#/components/schemas/OrgDomainEntryOrgConsole'
        dnsVerificationInstructions:
          type: string
          description: >-
            Plain-language reminder to add the ownership TXT from the domain’s DNS checklist, then use Verify DNS in the
            organization’s domain settings.
    OrgPatchDomainResponse:
      type: object
      required:
        - success
        - domain
      properties:
        success:
          type: boolean
        domain:
          $ref: '#/components/schemas/OrgDomainEntryOrgConsole'
        dnsVerificationInstructions:
          type: string
          description: >-
            Plain-language reminder to add the ownership TXT from the domain’s DNS checklist, then use Verify DNS in the
            organization’s domain settings.
    PatchOrgDomainRequest:
      type: object
      properties:
        status:
          type: string
          enum:
            - pending
            - failed
          description: Org self-serve reset only; go-live is via admin activate.
        regenerateToken:
          type: boolean
    OrgVerifyCustomDomainDnsSuccessResponse:
      type: object
      required:
        - success
        - hostname
        - status
        - verificationToken
        - challengeHost
        - expectedTxt
        - dnsTxtHost
        - dnsTxtValue
      properties:
        success:
          type: boolean
          enum:
            - true
        hostname:
          type: string
        status:
          type: string
          description: >-
            Domain row status after check (typically cname_pending_staff after first TXT success from pending/failed;
            legacy dns_verified possible)
        verificationToken:
          type: string
        challengeHost:
          type: string
          description: Same as dnsTxtHost (_mudbase-verify.<hostname>)
        expectedTxt:
          type: string
          description: Same as dnsTxtValue
        dnsTxtHost:
          type: string
        dnsTxtValue:
          type: string
        edge:
          $ref: '#/components/schemas/OrgEdgeHints'
          description: >-
            Present on deployments that serve managed edge TLS
        dnsRecords:
          type: array
          description: >-
            Same shape as `OrgDomainEntryWithDns.dnsRecords` when certificate provisioning ran after this successful
            verify; omit or empty when provisioning is disabled or not yet run.
          items:
            $ref: '#/components/schemas/OrgDnsRecord'
        flyCertificateStatus:
          type: string
          nullable: true
          description: Managed certificate status after verify when provisioning is active; null otherwise
        flyAcmeEnabled:
          type: boolean
          description: True when automated managed-certificate provisioning is configured for this deployment.
        flyAcmeDisabledReason:
          type: string
          nullable: true
          description: When `flyAcmeEnabled` is false, why automated provisioning did not run (ops misconfiguration hint).
        flyProvisionError:
          type: string
          nullable: true
          description: When provisioning is enabled but certificate issuance failed, the provider error message for support; null on success.
        flyLegacyStaffPipeline:
          type: boolean
          description: >-
            When true, the legacy staff pipeline is on: status may stay `cname_pending_staff` and staff
            approve-cname is required even if certificate provisioning succeeds.
    OrgVerifyCustomDomainDnsFailureResponse:
      type: object
      required:
        - success
        - code
        - error
        - status
        - verificationToken
        - challengeHost
        - expectedTxt
        - dnsTxtHost
        - dnsTxtValue
      properties:
        success:
          type: boolean
          enum:
            - false
        code:
          type: string
          example: dns_verification_failed
        error:
          type: string
        challengeHost:
          type: string
        expectedTxt:
          type: string
        dnsTxtHost:
          type: string
        dnsTxtValue:
          type: string
        status:
          type: string
        verificationToken:
          type: string
    OrgDomainsListResponse:
      type: object
      properties:
        domains:
          type: array
          items:
            $ref: '#/components/schemas/OrgDomainEntryOrgConsole'
        dnsVerificationInstructions:
          type: string
          description: >-
            Plain-language reminder to add the ownership TXT from each domain’s DNS checklist, then use Verify DNS in
            the organization’s domain settings.
        primaryHostname:
          type: string
          nullable: true
        apiBaseUrl:
          type: string
        maxDomains:
          type: integer
        customDomainAllowed:
          type: boolean
    ProvisionEnterpriseRequest:
      type: object
      required:
        - orgId
        - provisionRequestId
        - apiBaseUrl
        - dbRef
        - serverId
      properties:
        orgId:
          type: string
        provisionRequestId:
          type: string
        apiBaseUrl:
          type: string
        dbRef:
          type: string
        serverId:
          type: string
        region:
          type: string
        version:
          type: string
        forceOverride:
          type: boolean
    InviteMemberRequest:
      type: object
      required:
        - email
        - role
      properties:
        email:
          type: string
          format: email
        role:
          type: string
          enum:
            - admin
            - member
            - viewer
    Plan:
      type: object
      properties:
        name:
          type: string
        price:
          type: number
        currency:
          type: string
        interval:
          type: string
        features:
          type: array
          items:
            type: string
    Usage:
      type: object
      properties:
        projects:
          type: integer
        users:
          type: integer
        storage:
          type: integer
        bandwidth:
          type: integer
        apiCalls:
          type: integer
        dbReads:
          type: integer
        dbWrites:
          type: integer
    Limits:
      type: object
      properties:
        projects:
          type: integer
        users:
          type: integer
        storage:
          type: integer
        bandwidth:
          type: integer
        apiCalls:
          type: integer
        dbReads:
          type: integer
        dbWrites:
          type: integer
    Billing:
      type: object
      properties:
        nextBillingDate:
          type: string
          format: date-time
        paymentMethod:
          type: string
        lastPayment:
          type: object
          properties:
            amount:
              type: number
            date:
              type: string
              format: date-time
            status:
              type: string
    UsageResponse:
      type: object
      properties:
        usage:
          $ref: '#/components/schemas/Usage'
        limits:
          $ref: '#/components/schemas/Limits'
        plan:
          $ref: '#/components/schemas/Plan'
        billing:
          $ref: '#/components/schemas/Billing'
    Project:
      type: object
      properties:
        _id:
          type: string
        name:
          type: string
        description:
          type: string
        slug:
          type: string
        org:
          type: string
        auth:
          $ref: '#/components/schemas/AuthConfig'
        database:
          $ref: '#/components/schemas/DatabaseConfig'
        storage:
          $ref: '#/components/schemas/StorageConfig'
        settings:
          $ref: '#/components/schemas/ProjectSettings'
        usage:
          $ref: '#/components/schemas/ProjectUsage'
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    ProjectSettings:
      type: object
      description: >
        Project-level settings. Toggles for verification and default user status apply to project-based and role-based
        signup.
      properties:
        allowAnonymousAuth:
          type: boolean
          default: true
          description: Allow anonymous (unauthenticated) users
        requireEmailVerification:
          type: boolean
          default: true
          description: >-
            When true, users who sign up with email do not receive a token until they verify their email; login is
            blocked until verified.
        requirePhoneVerification:
          type: boolean
          default: false
          description: When true, users who sign in with phone (e.g. OTP) must have verified their phone before receiving a token.
        defaultUserAccountStatus:
          type: string
          enum:
            - pending
            - active
          default: active
          description: >
            Default account status for new signups. **active** = user can use the app immediately.

            **pending** = user must be approved by an org owner/admin (PATCH org user status to active) before they can
            perform protected operations.
        enableRealtime:
          type: boolean
          default: true
        enableStorage:
          type: boolean
          default: true
        enableFunctions:
          type: boolean
          default: false
    CreateProjectRequest:
      type: object
      required:
        - name
      properties:
        name:
          type: string
          example: Mudbase Platform
        description:
          type: string
          example: Main platform for Mudbase services
        slug:
          type: string
          example: mudbase-platform
      description: >
        Project settings (requireEmailVerification, requirePhoneVerification, defaultUserAccountStatus) are not accepted
        on create; use PATCH to update settings after creation.
    UpdateProjectRequest:
      type: object
      properties:
        name:
          type: string
          example: Mudbase Platform
        description:
          type: string
          example: Main platform for Mudbase services
        logoUrl:
          type: string
          format: uri
          description: >
            Public URL for the project logo/brand image. Prefer uploading via **POST /api/projects/{id}/logo** or **POST
            /api/projects/{orgId}/projects/{id}/logo** (stored under logo/project/ in platform storage). Used in
            project-related emails.
        settings:
          $ref: '#/components/schemas/ProjectSettings'
          description: >
            Update project settings. Toggle **requireEmailVerification** (default true), **requirePhoneVerification**
            (default false),

            and **defaultUserAccountStatus** (pending | active, default active) to control how new users sign up and
            when they can sign in.
          example:
            requireEmailVerification: true
            requirePhoneVerification: false
            defaultUserAccountStatus: active
        auth:
          $ref: '#/components/schemas/AuthConfig'
    AuthConfig:
      type: object
      properties:
        providers:
          type: array
          items:
            $ref: '#/components/schemas/AuthProvider'
        notifyOnNewSignIn:
          type: boolean
          default: false
          description: >
            When true, a "new sign-in detected" email is sent to the user on each project-based sign-in (local or
            OAuth).

            Counts against the org's messaging/email plan quota. Default false. Organization-based sign-in always sends
            this email (no quota deduction).
    AuthProvider:
      type: object
      properties:
        name:
          type: string
        enabled:
          type: boolean
        config:
          type: object
    DatabaseConfig:
      type: object
      properties:
        collections:
          type: array
          items:
            type: string
    StorageConfig:
      type: object
      properties:
        buckets:
          type: array
          items:
            type: string
    ProjectUsage:
      type: object
      properties:
        apiCalls:
          type: integer
        storage:
          type: integer
        bandwidth:
          type: integer
        dbReads:
          type: integer
        dbWrites:
          type: integer
    ProjectUsageResponse:
      type: object
      properties:
        usage:
          $ref: '#/components/schemas/ProjectUsage'
        limits:
          $ref: '#/components/schemas/Limits'
    Collection:
      type: object
      properties:
        _id:
          type: string
        name:
          type: string
        slug:
          type: string
        project:
          type: string
        fields:
          type: array
          items:
            $ref: '#/components/schemas/Field'
        permissions:
          type: array
          items:
            $ref: '#/components/schemas/Permission'
        settings:
          type: object
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    CreateCollectionRequest:
      type: object
      required:
        - name
        - fields
      properties:
        name:
          type: string
        slug:
          type: string
        fields:
          type: array
          items:
            $ref: '#/components/schemas/Field'
        permissions:
          type: array
          items:
            $ref: '#/components/schemas/Permission'
        settings:
          type: object
    UpdateCollectionRequest:
      type: object
      properties:
        name:
          type: string
        fields:
          type: array
          items:
            $ref: '#/components/schemas/Field'
        permissions:
          type: array
          items:
            $ref: '#/components/schemas/Permission'
        settings:
          type: object
    Field:
      type: object
      required:
        - name
        - type
      properties:
        name:
          type: string
        type:
          type: string
          enum:
            - string
            - number
            - boolean
            - date
            - datetime
            - email
            - url
            - text
            - array
            - object
            - reference
            - file
            - enum
            - json
        required:
          type: boolean
        unique:
          type: boolean
        default:
          oneOf:
            - type: string
            - type: number
            - type: boolean
        validation:
          type: object
        ui:
          type: object
    Permission:
      type: object
      properties:
        role:
          type: string
        actions:
          type: array
          items:
            type: string
            enum:
              - create
              - read
              - update
              - delete
        fields:
          type: array
          items:
            type: string
        condition:
          type: object
    DataListResponse:
      type: object
      properties:
        data:
          type: array
          items:
            type: object
            description: >-
              Document from the collection (includes _id, createdAt, updatedAt, and all collection fields). Additional
              fields are defined in the collection schema.
            properties:
              _id:
                type: string
                description: Document ID (MongoDB ObjectId) - use this as documentId in API calls
                example: 696bbe5b99eeb7f929a93e0b
              createdAt:
                type: string
                format: date-time
                description: Document creation timestamp
              updatedAt:
                type: string
                format: date-time
                description: Document last update timestamp
            additionalProperties: true
        pagination:
          $ref: '#/components/schemas/Pagination'
    DataResponse:
      type: object
      properties:
        message:
          type: string
        data:
          type: object
    Pagination:
      type: object
      properties:
        page:
          type: integer
        limit:
          type: integer
        total:
          type: integer
        totalPages:
          type: integer
    FileUploadResponse:
      type: object
      properties:
        success:
          type: boolean
          description: Whether the upload succeeded.
        message:
          type: string
        file:
          description: >-
            Uploaded file metadata (singular). Kept for backward compatibility.
            The server now returns a files array; callers should prefer files[0]
            when available.
          $ref: '#/components/schemas/FileMetadata'
        files:
          type: array
          description: >-
            Uploaded file metadata array. The server returns an array even for a
            single-file upload. Populate from the server files field; fall back
            to [file] when files is absent.
          items:
            $ref: '#/components/schemas/FileMetadata'
    FileMetadata:
      type: object
      properties:
        _id:
          type: string
        filename:
          type: string
        originalName:
          type: string
        mimeType:
          type: string
        size:
          type: integer
        url:
          type: string
        publicUrl:
          type: string
        bucket:
          type: string
        projectId:
          type: string
        isPublic:
          type: boolean
        uploadedBy:
          type: string
        createdAt:
          type: string
          format: date-time
    FileListResponse:
      type: object
      properties:
        files:
          type: array
          items:
            $ref: '#/components/schemas/FileMetadata'
        pagination:
          $ref: '#/components/schemas/Pagination'
    ApiKey:
      type: object
      properties:
        _id:
          type: string
        name:
          type: string
        project:
          $ref: '#/components/schemas/ProjectSummary'
        permissions:
          type: array
          items:
            $ref: '#/components/schemas/ApiKeyPermission'
        rateLimit:
          $ref: '#/components/schemas/RateLimit'
        usage:
          $ref: '#/components/schemas/ApiKeyUsage'
        isActive:
          type: boolean
        expiresAt:
          type: string
          format: date-time
        createdBy:
          $ref: '#/components/schemas/UserSummary'
        createdAt:
          type: string
          format: date-time
    ApiKeyWithSecret:
      allOf:
        - $ref: '#/components/schemas/ApiKey'
        - type: object
          properties:
            secret:
              type: string
    ApiKeyPermission:
      type: object
      required:
        - resource
        - actions
      properties:
        resource:
          type: string
          enum:
            - auth
            - database
            - storage
            - functions
            - realtime
            - messaging
          description: Resource scope for this permission (auth, database, storage, functions, realtime, messaging)
        actions:
          type: array
          items:
            type: string
            enum:
              - create
              - read
              - update
              - delete
          description: Allowed actions on the resource
    CreateApiKeyRequest:
      type: object
      required:
        - name
        - projectId
      properties:
        name:
          type: string
          minLength: 2
          maxLength: 100
        projectId:
          type: string
          pattern: ^[0-9a-fA-F]{24}$
          description: MongoDB ObjectId of the project
        permissions:
          type: array
          items:
            $ref: '#/components/schemas/ApiKeyPermission'
          description: >-
            Optional. Permission objects (resource + actions). Omit or pass [] for full access (all resources and
            actions). Include only the entries you want; remove resources or actions to restrict the key.
        rateLimit:
          $ref: '#/components/schemas/RateLimit'
        expiresAt:
          type: string
          format: date-time
          description: Optional. When provided, must be a valid ISO 8601 date-time in the future. Omit for no expiration.
    UpdateApiKeyRequest:
      type: object
      properties:
        name:
          type: string
          minLength: 2
          maxLength: 100
        permissions:
          type: array
          items:
            $ref: '#/components/schemas/ApiKeyPermission'
        rateLimit:
          $ref: '#/components/schemas/RateLimit'
        isActive:
          type: boolean
    RateLimit:
      type: object
      properties:
        requests:
          type: integer
        window:
          type: integer
    ApiKeyUsage:
      type: object
      properties:
        requests:
          type: integer
        lastUsed:
          type: string
          format: date-time
    ApiKeyUsageResponse:
      type: object
      properties:
        usage:
          $ref: '#/components/schemas/ApiKeyUsage'
        rateLimit:
          $ref: '#/components/schemas/RateLimit'
        isActive:
          type: boolean
        expiresAt:
          type: string
          format: date-time
    ProjectSummary:
      type: object
      properties:
        _id:
          type: string
        name:
          type: string
        slug:
          type: string
    UserSummary:
      type: object
      properties:
        _id:
          type: string
        firstName:
          type: string
        lastName:
          type: string
        email:
          type: string
          format: email
    CreateBucketRequest:
      type: object
      required:
        - name
      properties:
        name:
          type: string
          description: The name of the bucket
        isPublic:
          type: boolean
          default: false
          description: Whether the bucket is publicly accessible
        settings:
          type: object
          description: Additional bucket settings
    BucketResponse:
      type: object
      properties:
        success:
          type: boolean
        message:
          type: string
        bucket:
          $ref: '#/components/schemas/Bucket'
    Bucket:
      type: object
      properties:
        _id:
          type: string
        name:
          type: string
        projectId:
          type: string
        isPublic:
          type: boolean
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    BucketListResponse:
      type: object
      properties:
        success:
          type: boolean
        buckets:
          type: array
          items:
            $ref: '#/components/schemas/Bucket'
        pagination:
          $ref: '#/components/schemas/Pagination'
    UpdateBucketRequest:
      type: object
      properties:
        name:
          type: string
          description: Updated name of the bucket
        isPublic:
          type: boolean
          description: Update whether the bucket is publicly accessible
        settings:
          type: object
          description: Updated bucket settings
    FileResponse:
      type: object
      properties:
        success:
          type: boolean
        file:
          $ref: '#/components/schemas/FileMetadata'
    SignedUrlResponse:
      type: object
      properties:
        success:
          type: boolean
        url:
          type: string
          description: Signed URL for file access
        expiresAt:
          type: string
          format: date-time
          description: Expiration time of the signed URL (optional - some endpoints return expiresIn instead)
        expiresIn:
          type: integer
          description: Time-to-live in seconds for the signed URL (optional)
    PresignedPostResponse:
      type: object
      properties:
        key:
          type: string
          description: Object key clients should upload to
        url:
          type: string
          description: Presigned URL to PUT the file body to directly
        method:
          type: string
          enum:
            - PUT
          description: HTTP method the client must use against `url` (always PUT - the object storage backend does not implement a POST-based upload API)
        headers:
          type: object
          description: >-
            Headers the client must send with the PUT request (e.g. Content-Type) - mismatching these from what was
            signed causes a SignatureDoesNotMatch error
        expiresIn:
          type: integer
          description: Expiration of the presigned URL in seconds
        maxFileUploadBytes:
          type: integer
          format: int64
          description: >-
            Maximum upload size in bytes for this org plan. Not enforced by the presigned URL itself (PUT has no
            content-length-range equivalent) - checked server-side by /api/files/upload/confirm after the upload
            completes
    ConfirmUploadResponse:
      type: object
      properties:
        fileId:
          type: string
        status:
          type: string
          enum:
            - ok
            - quarantined
            - error
        scan:
          type: object
          description: Virus scan result (provider, status, detections, raw analysis)
          properties:
            status:
              type: string
            provider:
              type: string
            detections:
              type: integer
            analysis:
              type: object
              description: Raw analysis object returned by the scanner (e.g., VirusTotal)
    WebhookListResponse:
      type: object
      properties:
        webhooks:
          type: array
          items:
            $ref: '#/components/schemas/WebhookLog'
        total:
          type: integer
        page:
          type: integer
        limit:
          type: integer
        totalPages:
          type: integer
    WebhookLog:
      type: object
      description: >
        One **outbound delivery attempt** (Mudbase HTTP client → your `url`). **`_id`** is what the API calls
        **`webhookId`** in **`POST /api/webhooks/trigger`** and **`POST /api/webhooks/retry/{webhookId}`**. The string
        field **`webhookId`** below is an internal correlation id (e.g. `manual-<timestamp>`), not the path parameter
        for retry.
      properties:
        _id:
          type: string
          description: MongoDB id — use as `webhookId` path param for retry
        org:
          type: string
          description: Organization that owns the project
        project:
          type: string
          description: Project id this delivery belongs to
        webhookId:
          type: string
          description: Internal correlation string (e.g. manual-173…), not the retry path id
        url:
          type: string
        method:
          type: string
          enum:
            - GET
            - POST
            - PUT
            - PATCH
            - DELETE
        event:
          type: string
        status:
          type: string
          enum:
            - pending
            - success
            - failed
            - retrying
        payload:
          type: object
          description: JSON body sent to your endpoint
        headers:
          type: object
          description: Outbound request headers (e.g. X-MUDBASE-Event, Content-Type)
        response:
          type: object
          description: Last HTTP response from your server (if any)
          properties:
            status:
              type: integer
              description: HTTP status code from your endpoint
            body:
              type: object
              description: Parsed JSON when possible; otherwise structure varies
            headers:
              type: object
        duration:
          type: integer
          description: Round-trip time in milliseconds
        attempts:
          type: integer
        maxAttempts:
          type: integer
        error:
          type: string
          nullable: true
        nextRetry:
          type: string
          format: date-time
          nullable: true
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    TriggerWebhookRequest:
      type: object
      required:
        - projectId
        - url
        - event
        - payload
      properties:
        projectId:
          type: string
          format: objectid
          description: Target project (must belong to your org)
        url:
          type: string
          format: uri
          description: HTTPS URL validated against SSRF rules
        event:
          type: string
          description: Event name (sent as X-MUDBASE-Event)
        payload:
          type: object
          description: JSON body POSTed to your endpoint
        method:
          type: string
          enum:
            - GET
            - POST
            - PUT
            - PATCH
            - DELETE
          default: POST
    TriggerWebhookResponse:
      type: object
      required:
        - message
        - webhookId
      properties:
        message:
          type: string
          example: Webhook triggered successfully
        webhookId:
          type: string
          format: objectid
          description: WebhookLog._id for this delivery; use in POST /api/webhooks/retry/{webhookId}
    RetryWebhookResponse:
      type: object
      required:
        - message
        - webhookId
      properties:
        message:
          type: string
          example: Webhook retry initiated
        webhookId:
          type: string
          format: objectid
          description: Same log _id you passed in the path
    WebhookStatsResponse:
      type: object
      required:
        - statusStats
        - eventStats
        - period
      properties:
        statusStats:
          type: array
          description: Grouped by delivery status
          items:
            type: object
            properties:
              _id:
                type: string
                description: Status key (pending, success, failed, retrying)
              count:
                type: integer
              avgDuration:
                type: number
                nullable: true
                description: Average duration in ms for that status bucket
        eventStats:
          type: array
          description: Grouped by event name
          items:
            type: object
            properties:
              _id:
                type: string
                description: Event name
              count:
                type: integer
              successRate:
                type: number
                description: Fraction of logs with status success (0–1)
        period:
          type: string
          example: 7 days
    FunctionListResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            functions:
              type: array
              items:
                $ref: '#/components/schemas/Function'
            pagination:
              $ref: '#/components/schemas/Pagination'
    Function:
      type: object
      properties:
        _id:
          type: string
        name:
          type: string
        description:
          type: string
        projectId:
          type: string
        trigger:
          $ref: '#/components/schemas/FunctionTrigger'
        stats:
          $ref: '#/components/schemas/FunctionStats'
        isActive:
          type: boolean
        createdBy:
          type: string
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    CreateFunctionRequest:
      type: object
      required:
        - name
        - code
        - trigger
      properties:
        name:
          type: string
        description:
          type: string
        code:
          type: string
          description: Function body (async, has access to payload, db, files, messaging, utils, env, console)
        trigger:
          $ref: '#/components/schemas/FunctionTrigger'
        environment:
          type: object
          additionalProperties:
            type: string
          description: Per-function env vars injected into sandbox
    UpdateFunctionRequest:
      type: object
      properties:
        name:
          type: string
        description:
          type: string
        code:
          type: string
        trigger:
          $ref: '#/components/schemas/FunctionTrigger'
        environment:
          type: object
        isActive:
          type: boolean
        limits:
          type: object
          properties:
            timeout:
              type: integer
              description: Max execution time in ms (default 30000)
            maxPayloadSize:
              type: integer
              description: Max payload size in bytes (default 1MB)
            maxExecutionsPerMinute:
              type: integer
            maxExecutionsPerHour:
              type: integer
        retryPolicy:
          type: object
          properties:
            enabled:
              type: boolean
            maxRetries:
              type: integer
            backoffMs:
              type: integer
        versionComment:
          type: string
          description: Comment for version when code is updated
    FunctionTrigger:
      type: object
      required:
        - type
      properties:
        type:
          type: string
          enum:
            - http
            - event
            - document
            - file
            - webhook
            - cron
            - messaging
          description: Trigger type
        event:
          type: string
          description: Event name (e.g. create, update, delete for document; uploaded, deleted for file)
        schedule:
          type: string
          description: For cron - minutely, hourly, daily, weekly, or custom cron expression
        path:
          type: string
          description: HTTP path for http triggers
        method:
          type: string
          enum:
            - GET
            - POST
            - PUT
            - DELETE
        collectionId:
          type: string
          format: objectid
          description: For document triggers - filter by collection
        bucketId:
          type: string
          format: objectid
          description: For file triggers - filter by bucket
    FunctionStats:
      type: object
      properties:
        totalExecutions:
          type: integer
        successfulExecutions:
          type: integer
        failedExecutions:
          type: integer
        avgExecutionTime:
          type: number
        lastExecution:
          type: string
          format: date-time
    FunctionResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          $ref: '#/components/schemas/Function'
    FunctionExecutionResponse:
      type: object
      description: |
        Response from Execute function / Simulate trigger. Both endpoints are async (202) and only
        hand back an executionId — see FunctionExecutionStatusResponse for the real outcome.
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            executionId:
              type: string
            status:
              type: string
              enum:
                - queued
    FunctionExecutionStatusResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            executionId:
              type: string
            status:
              type: string
              enum:
                - queued
                - provisioning
                - running
                - success
                - failed
                - timeout
            durationMs:
              type: integer
              description: Duration in milliseconds (null until completed)
            result:
              type: object
              nullable: true
            error:
              type: string
              nullable: true
            errorClass:
              type: string
              nullable: true
            logs:
              type: object
              properties:
                stdout:
                  type: string
                stderr:
                  type: string
                truncated:
                  type: boolean
                bytes:
                  type: integer
            machine:
              type: object
              nullable: true
            createdAt:
              type: string
              format: date-time
            startedAt:
              type: string
              format: date-time
              nullable: true
            completedAt:
              type: string
              format: date-time
              nullable: true
    FunctionLogsResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            executions:
              type: array
              items:
                $ref: '#/components/schemas/FunctionExecution'
            stats:
              $ref: '#/components/schemas/FunctionStats'
    FunctionExecution:
      type: object
      properties:
        _id:
          type: string
        executedAt:
          type: string
          format: date-time
        executionTime:
          type: integer
        success:
          type: boolean
        payload:
          type: object
        result:
          type: object
        error:
          type: string
        triggerType:
          type: string
        triggerEvent:
          type: string
        invokedBy:
          type: string
          enum:
            - manual
            - api_key
            - trigger
            - cron
        retryCount:
          type: integer
    PushNotificationRequest:
      type: object
      required:
        - title
        - body
      description: >
        Provide at least one target: `tokens` (registered device tokens), `endpoints` (registered
        Web Push subscription endpoints), `userIds` (Web Push subscriptions associated to those user
        ids), or `webPushBroadcast: true` (every enabled Web Push subscription in the project). A
        single send can target both the device-token channel and the native Web Push channel at once.
      properties:
        tokens:
          type: array
          description: Registered device push tokens to deliver to (device-token channel).
          items:
            type: string
        endpoints:
          type: array
          description: >
            Registered Web Push subscription endpoints to deliver to (native Web Push channel).
          items:
            type: string
        userIds:
          type: array
          description: >
            Deliver to every Web Push subscription registered under these user ids (native Web Push
            channel).
          items:
            type: string
        webPushBroadcast:
          type: boolean
          description: >
            When true, deliver to every enabled Web Push subscription registered to the project
            (native Web Push channel). Ignored when the project has not enabled native Web Push.
        title:
          type: string
        body:
          type: string
        data:
          type: object
        imageUrl:
          type: string
    EmailRequest:
      type: object
      required:
        - to
        - subject
      properties:
        to:
          oneOf:
            - type: string
            - type: array
              items:
                type: string
        subject:
          type: string
        html:
          type: string
        text:
          type: string
        templateId:
          type: string
        templateData:
          type: object
    SMSRequest:
      type: object
      required:
        - to
        - message
      properties:
        to:
          type: string
        message:
          type: string
        from:
          type: string
    MessageSentResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            _id:
              type: string
            type:
              type: string
            status:
              type: string
            recipients:
              type: integer
            successCount:
              type: integer
            failureCount:
              type: integer
            messageId:
              type: string
            sentAt:
              type: string
              format: date-time
    DeviceRegisterRequest:
      type: object
      required:
        - token
      properties:
        token:
          type: string
          description: The device push token issued to your app by its push client.
        platform:
          type: string
          enum:
            - ios
            - android
            - web
            - unknown
          default: unknown
          description: The device platform. Defaults to `unknown` when omitted or unrecognized.
    DeviceToken:
      type: object
      properties:
        token:
          type: string
        platform:
          type: string
          enum:
            - ios
            - android
            - web
            - unknown
        lastSeenAt:
          type: string
          format: date-time
        createdAt:
          type: string
          format: date-time
    DeviceRegisteredResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            token:
              type: string
            platform:
              type: string
              enum:
                - ios
                - android
                - web
                - unknown
            lastSeenAt:
              type: string
              format: date-time
    DeviceListResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: array
          items:
            $ref: '#/components/schemas/DeviceToken'
    DeviceUnregisterRequest:
      type: object
      required:
        - token
      properties:
        token:
          type: string
          description: The device push token to remove from the project.
    DeviceUnregisteredResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            removed:
              type: boolean
              description: True if a matching token was removed; false if none was registered.
    PushSentResponse:
      type: object
      description: >
        Result of a push send, summarized per channel. `channels.fcm` covers the device-token
        channel and `channels.webPush` the native Web Push channel; each is `null` when that channel
        had no targets in the request.
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            success:
              type: boolean
              description: True when at least one recipient across any channel was delivered to.
            messageId:
              type: string
            successCount:
              type: integer
            failureCount:
              type: integer
            channels:
              type: object
              properties:
                fcm:
                  nullable: true
                  type: object
                  properties:
                    successCount:
                      type: integer
                    failureCount:
                      type: integer
                webPush:
                  nullable: true
                  type: object
                  properties:
                    successCount:
                      type: integer
                    failureCount:
                      type: integer
                    pruned:
                      type: integer
                      description: >
                        Subscriptions the push service reported as gone (404/410) and that were
                        pruned during this send.
            rejectedTokens:
              type: array
              description: >
                Device tokens that were passed but are not registered to the project, and so were
                dropped. Omitted when empty.
              items:
                type: string
    WebPushConfigResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            enabled:
              type: boolean
              description: Whether native Web Push is enabled for this project.
            hasKeys:
              type: boolean
              description: Whether a VAPID keypair has been provisioned.
            publicKey:
              type: string
              nullable: true
              description: >
                The VAPID application-server public key clients subscribe with. Null when native Web
                Push is not enabled.
            vapidSubject:
              type: string
              nullable: true
              description: RFC 8292 contact subject (a `mailto:` address or `https` URL).
            generatedAt:
              type: string
              format: date-time
              nullable: true
              description: When the current VAPID keypair was generated.
    WebPushConfigPatchRequest:
      type: object
      description: >
        All fields optional. `enabled` toggles native Web Push (and provisions a keypair on first
        enable); `rotateKeys` regenerates the keypair (invalidating existing subscriptions); `subject`
        sets the RFC 8292 contact URI.
      properties:
        enabled:
          type: boolean
        rotateKeys:
          type: boolean
        subject:
          type: string
          description: A `mailto:` address or an `https` URL.
    WebPushPublicKeyResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            enabled:
              type: boolean
            publicKey:
              type: string
              nullable: true
              description: >
                The VAPID application-server public key, or null when native Web Push is not enabled.
    WebPushSubscription:
      type: object
      description: >
        A browser `PushSubscription` from `pushManager.subscribe()` - the push-service `endpoint` plus
        the `p256dh` / `auth` keys the server needs to encrypt a payload for that endpoint.
      required:
        - endpoint
        - keys
      properties:
        endpoint:
          type: string
          description: The push-service endpoint URL returned by `pushManager.subscribe()`.
        keys:
          type: object
          required:
            - p256dh
            - auth
          properties:
            p256dh:
              type: string
              description: The subscription's P-256 ECDH public key (base64url).
            auth:
              type: string
              description: The subscription's auth secret (base64url).
    WebPushSubscribeRequest:
      type: object
      required:
        - subscription
      properties:
        subscription:
          $ref: '#/components/schemas/WebPushSubscription'
        userId:
          type: string
          description: Optional end-user id to associate with this subscription, for targeted sends.
        deviceId:
          type: string
          description: Optional client-supplied device identifier.
    WebPushSubscribeResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            endpoint:
              type: string
            userId:
              type: string
              nullable: true
            lastSeenAt:
              type: string
              format: date-time
    WebPushSubscriptionSummary:
      type: object
      description: A registered Web Push subscription. The encryption keys are never returned.
      properties:
        endpoint:
          type: string
        userId:
          type: string
        deviceId:
          type: string
        userAgent:
          type: string
        disabled:
          type: boolean
        lastSeenAt:
          type: string
          format: date-time
        createdAt:
          type: string
          format: date-time
    WebPushSubscriptionListResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: array
          items:
            $ref: '#/components/schemas/WebPushSubscriptionSummary'
    WebPushUnsubscribeRequest:
      type: object
      required:
        - endpoint
      properties:
        endpoint:
          type: string
          description: The push-service endpoint of the subscription to remove.
    WebPushUnsubscribeResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            removed:
              type: boolean
              description: >
                True if a matching subscription was removed; false if none was registered.
    MessageHistoryResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            messages:
              type: array
              items:
                $ref: '#/components/schemas/Message'
            pagination:
              $ref: '#/components/schemas/Pagination'
    Message:
      type: object
      properties:
        _id:
          type: string
        type:
          type: string
          enum:
            - push
            - email
            - sms
        title:
          type: string
        body:
          type: string
        subject:
          type: string
        recipients:
          type: integer
        successCount:
          type: integer
        failureCount:
          type: integer
        status:
          type: string
          enum:
            - sent
            - failed
            - pending
        sentAt:
          type: string
          format: date-time
    MessageStatsResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            totalMessages:
              type: integer
            byType:
              type: object
              properties:
                push:
                  type: integer
                email:
                  type: integer
                sms:
                  type: integer
            byStatus:
              type: object
              properties:
                sent:
                  type: integer
                failed:
                  type: integer
                pending:
                  type: integer
            successRate:
              type: number
            period:
              type: object
              properties:
                startDate:
                  type: string
                  format: date-time
                endDate:
                  type: string
                  format: date-time
    UsageStatsResponse:
      type: object
      properties:
        usage:
          $ref: '#/components/schemas/Usage'
        limits:
          $ref: '#/components/schemas/Limits'
        plan:
          $ref: '#/components/schemas/Plan'
        period:
          type: string
        percentages:
          type: object
          properties:
            apiCalls:
              type: number
            storage:
              type: number
            bandwidth:
              type: number
    ProjectUsageStatsResponse:
      type: object
      properties:
        project:
          type: object
          properties:
            id:
              type: string
            name:
              type: string
        usage:
          $ref: '#/components/schemas/ProjectUsage'
        period:
          type: string
    UsageTrendsResponse:
      type: object
      properties:
        trends:
          type: array
          items:
            type: object
            properties:
              _id:
                type: object
                properties:
                  year:
                    type: integer
                  month:
                    type: integer
                  day:
                    type: integer
              apiCalls:
                type: integer
              storage:
                type: integer
              bandwidth:
                type: integer
              dbReads:
                type: integer
              dbWrites:
                type: integer
        period:
          type: string
    ProjectDashboardOverviewResponse:
      type: object
      required:
        - success
        - data
      properties:
        success:
          type: boolean
          example: true
        data:
          $ref: '#/components/schemas/DashboardOverviewData'
    DashboardOverviewData:
      type: object
      properties:
        project:
          type: object
          properties:
            id:
              type: string
            name:
              type: string
            slug:
              type: string
        requests:
          type: object
          properties:
            today:
              type: integer
              description: Billing trackApiCall count (UTC day)
            yesterday:
              type: integer
            latencyTrackedToday:
              type: integer
              description: UsageStat latencyCount for this project (middleware-metered responses)
            latencyTrackedYesterday:
              type: integer
            meteringNote:
              type: string
            changePct:
              type: number
            direction:
              type: string
              enum:
                - up
                - down
                - flat
        activeUsers:
          type: object
          properties:
            last24h:
              type: integer
            last7d:
              type: integer
            last30d:
              type: integer
            changePct7d:
              type: number
            direction7d:
              type: string
            realtimeConnected:
              type: integer
        latency:
          type: object
          description: >-
            Per-project weighted mean latency from UsageStat for routes in openapi-docs.yaml (customer/project API
            only).
          properties:
            scope:
              type: string
              enum:
                - project_openapi_doc
            avgMsToday:
              type: integer
              nullable: true
            avgMs7d:
              type: integer
              nullable: true
            latencySamplesToday:
              type: integer
              description: Count of openapi-docs–scoped latency samples for this project (UTC today)
            latencyNeedsTraffic:
              type: boolean
            interpretation:
              type: string
              description: Why mean can differ from typical latency; points to latency-insights
            instanceRollup:
              type: object
              nullable: true
              description: In-process p50/p95/p99 for this Node instance (ephemeral; multi-pod differs per replica)
              properties:
                scope:
                  type: string
                  enum:
                    - instance_recent
                p50Ms:
                  type: integer
                  nullable: true
                p95Ms:
                  type: integer
                  nullable: true
                p99Ms:
                  type: integer
                  nullable: true
                meanMs:
                  type: integer
                  nullable: true
                samplesApprox:
                  type: integer
                templatesTracked:
                  type: integer
            topRoutesByImpactHint:
              type: array
              description: Top route templates by impact score on this instance (debugging hint)
              items:
                type: object
                properties:
                  routeKey:
                    type: string
                  p50Ms:
                    type: integer
                    nullable: true
                  p95Ms:
                    type: integer
                    nullable: true
                  count:
                    type: integer
                  impactScore:
                    type: integer
        uptime:
          type: object
          description: >-
            Organization-wide uptime KPI; platformProbe* is infra (Mongo); projectHttp* is this project only for
            comparison.
          properties:
            scope:
              type: string
              enum:
                - organization
            displayPct30d:
              type: number
              nullable: true
            displaySource:
              type: string
            isPreliminary:
              type: boolean
            platformProbePct30d:
              type: number
              nullable: true
            platformSamples:
              type: integer
            platformOkSamples:
              type: integer
            orgHttpNon5xxPct30d:
              type: number
              nullable: true
            orgHttpSampled30d:
              type: integer
            orgHttp5xx30d:
              type: integer
              description: Metered 5xx count from UsageStat (trackApiCall)
            projectHttp5xx30d:
              type: integer
              description: This project’s metered 5xx count (30d)
            globalHttpNon5xxPct30d:
              type: number
              nullable: true
              description: Deprecated alias for orgHttpNon5xxPct30d
            globalHttpSampled30d:
              type: integer
              description: Deprecated alias for orgHttpSampled30d
            requestNon5xxPct30d:
              type: number
              nullable: true
              description: Deprecated alias for orgHttpNon5xxPct30d
            requestSampled30d:
              type: integer
              description: Deprecated alias for orgHttpSampled30d
            projectHttpNon5xxPct30d:
              type: number
              nullable: true
            projectHttpSampled30d:
              type: integer
            help:
              type: string
        requestVolume14d:
          type: array
          items:
            type: object
            properties:
              date:
                type: string
                example: '2025-03-18'
              apiCalls:
                type: integer
              latencyTracked:
                type: integer
                description: Middleware-metered responses that day (UsageStat latencyCount)
        recentActivity:
          type: array
          items:
            $ref: '#/components/schemas/DashboardActivityItem'
        generatedAt:
          type: string
          format: date-time
    DashboardActivityItem:
      type: object
      properties:
        id:
          type: string
        at:
          type: string
          format: date-time
        action:
          type: string
        title:
          type: string
        detail:
          type: string
        actorEmail:
          type: string
          nullable: true
    ProjectUsageSummaryResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          description: Contains requests, activeUsers, requestVolume14d, latency, platformUptimePct30d, platformUptimeSamples
    MonitoringLogsResponse:
      type: object
      properties:
        logs:
          type: array
          items:
            type: object
            properties:
              id:
                type: string
              timestamp:
                type: string
                format: date-time
              level:
                type: string
              message:
                type: string
              action:
                type: string
              activityTitle:
                type: string
              activityDetail:
                type: string
              user:
                type: object
                nullable: true
                properties:
                  id:
                    type: string
                  email:
                    type: string
              project:
                type: object
                nullable: true
              metadata:
                type: object
        count:
          type: integer
        page:
          type: integer
        limit:
          type: integer
        total:
          type: integer
        totalPages:
          type: integer
    MonitoringAnalyticsResponse:
      type: object
      properties:
        period:
          type: string
        granularity:
          type: string
        days:
          type: integer
          description: Present when rolling window used
        stats:
          type: array
          items:
            type: object
            properties:
              date:
                type: string
              apiCalls:
                type: integer
              dbReads:
                type: integer
              dbWrites:
                type: integer
              storage:
                type: integer
              bandwidth:
                type: integer
        totals:
          type: object
          properties:
            totalApiCalls:
              type: integer
            totalDbReads:
              type: integer
            totalDbWrites:
              type: integer
            totalStorage:
              type: integer
            totalBandwidth:
              type: integer
    MonitoringPerformanceResponse:
      type: object
      properties:
        period:
          type: string
        metrics:
          type: object
          properties:
            totalRequests:
              type: integer
            avgResponseTime:
              type: number
            minResponseTime:
              type: number
            maxResponseTime:
              type: number
            errorCount:
              type: integer
            successCount:
              type: integer
            successRate:
              type: number
            errorRate:
              type: number
            latencySource:
              type: string
              description: usage_stat when filled from UsageStat
        topEndpoints:
          type: array
          items:
            type: object
    SearchResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            results:
              type: array
              items:
                $ref: '#/components/schemas/SearchResult'
            pagination:
              $ref: '#/components/schemas/Pagination'
            query:
              type: string
            searchTime:
              type: integer
    SearchResult:
      type: object
      properties:
        collection:
          type: string
        item:
          type: object
          properties:
            _id:
              type: string
            score:
              type: number
        highlight:
          type: object
    HealthResponse:
      type: object
      properties:
        status:
          type: string
          enum:
            - healthy
            - unhealthy
        timestamp:
          type: string
          format: date-time
        services:
          type: object
          properties:
            database:
              type: string
            redis:
              type: string
            storage:
              type: string
            email:
              type: string
            sms:
              type: string
        version:
          type: string
        uptime:
          type: integer
    SystemStatusResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            uptime:
              type: integer
            memory:
              type: object
              properties:
                used:
                  type: integer
                total:
                  type: integer
                percentage:
                  type: number
            cpu:
              type: object
              properties:
                usage:
                  type: number
                cores:
                  type: integer
            requests:
              type: object
              properties:
                total:
                  type: integer
                successful:
                  type: integer
                errors:
                  type: integer
                errorRate:
                  type: number
            database:
              type: object
              properties:
                connections:
                  type: integer
                maxConnections:
                  type: integer
                responseTime:
                  type: integer
            storage:
              type: object
              properties:
                used:
                  type: integer
                available:
                  type: integer
                percentage:
                  type: number
    MessageResponse:
      type: object
      properties:
        message:
          type: string
    EmailTemplateCatalogItem:
      type: object
      description: One row from GET /email/templates (full catalog for the project).
      properties:
        name:
          type: string
        isCustomized:
          type: boolean
          description: True if this project has a stored override for this template name.
        effectiveSource:
          type: string
          enum:
            - project
            - global
            - builtin
          description: Which layer is used at send time for this name.
        subjectSnippet:
          type: string
        updatedAt:
          type: string
          format: date-time
          nullable: true
        version:
          type: integer
          nullable: true
    EmailTemplateResolved:
      type: object
      description: Effective template body (project override, else global, else built-in).
      properties:
        name:
          type: string
        subject:
          type: string
        htmlBody:
          type: string
        textBody:
          type: string
        variables:
          type: array
          items:
            type: string
        updatedAt:
          type: string
          format: date-time
          nullable: true
        version:
          type: integer
          nullable: true
        isProjectOverride:
          type: boolean
        effectiveSource:
          type: string
          enum:
            - project
            - global
            - builtin
    ProjectEmailSendRequest:
      type: object
      description: >
        Either `template` (with optional `data`) or both `subject` and `html` must be provided. `to` may be a string or
        array of strings.

        For named templates, **`data`** should supply values for `{{placeholders}}` (see **Email** tag description for
        the full list).
      properties:
        template:
          type: string
          description: Registered template name resolved by the email worker
        to:
          oneOf:
            - type: string
            - type: array
              items:
                type: string
        data:
          type: object
          additionalProperties: true
        subject:
          type: string
        html:
          type: string
        idempotencyKey:
          type: string
        brandingScope:
          type: string
          enum:
            - platform
            - project
          description: Email layout branding; defaults from project context when omitted
    ProjectSmtpSettingsPublic:
      type: object
      properties:
        enabled:
          type: boolean
        host:
          type: string
        port:
          type: integer
        secure:
          type: boolean
        authUser:
          type: string
        hasPassword:
          type: boolean
        fromName:
          type: string
        fromEmail:
          type: string
        domainVerifiedAt:
          type: string
          format: date-time
          nullable: true
    ProjectSmtpPatchRequest:
      type: object
      properties:
        enabled:
          type: boolean
        host:
          type: string
        port:
          type: integer
        secure:
          type: boolean
        authUser:
          type: string
        authPass:
          type: string
          description: SMTP password; stored encrypted, never returned on GET
        fromName:
          type: string
        fromEmail:
          type: string
        domainVerifiedAt:
          type: string
          format: date-time
          nullable: true
    ProjectSmtpTestRequest:
      type: object
      required:
        - to
      properties:
        to:
          type: string
          format: email
          description: Recipient for verification and test message
        useSaved:
          type: boolean
          default: true
          description: When true, use saved SMTP config; otherwise supply host/auth fields below
        host:
          type: string
        port:
          type: integer
        secure:
          type: boolean
        authUser:
          type: string
        authPass:
          type: string
        fromEmail:
          type: string
        fromName:
          type: string
    ProjectSmsByoPublic:
      type: object
      properties:
        enabled:
          type: boolean
        provider:
          type: string
          enum:
            - twilio
            - termii
            - africastalking
            - none
        defaultFrom:
          type: string
        hasCredentials:
          type: boolean
    ProjectSmsByoPatchRequest:
      type: object
      properties:
        enabled:
          type: boolean
        provider:
          type: string
          enum:
            - twilio
            - termii
            - africastalking
            - none
        defaultFrom:
          type: string
          description: >-
            Default sender (E.164 for Twilio; Termii/Africa's Talking may use alphanumeric or approved sender IDs per
            provider rules).
        config:
          type: object
          additionalProperties: true
          description: |
            Provider credentials and options (encrypted at rest). Required keys when enabling BYO:
            **twilio** — `accountSid`, `authToken`. Optional `from`.
            **termii** — `apiKey`. Optional `from`.
            **africastalking** — `username`, `apiKey`. Optional `from`.
    FeatureNotAllowedError:
      type: object
      description: Returned when an app-role feature gate denies access (HTTP 403)
      required:
        - success
        - error
      properties:
        success:
          type: boolean
          example: false
        error:
          type: string
          example: feature_not_allowed
        resource:
          type: string
          example: messaging
        action:
          type: string
          example: email
        message:
          type: string
          example: Your role does not have permission to send email for this project.
    Error:
      type: object
      properties:
        error:
          type: string
        code:
          type: string
        details:
          oneOf:
            - type: string
            - type: object
        timestamp:
          type: string
          format: date-time
        path:
          type: string
        requestId:
          type: string
    CollectionAction:
      type: string
      description: A single CRUD action grantable on a collection
      enum:
        - create
        - read
        - update
        - delete
    CollectionActionList:
      type: array
      description: List of CRUD actions granted on a collection
      items:
        $ref: '#/components/schemas/CollectionAction'
    CollectionPermissionRule:
      type: object
      description: Explicit actions + row-level conditions granted on a collection
      properties:
        actions:
          type: array
          items:
            $ref: '#/components/schemas/CollectionAction'
        conditions:
          type: object
  responses:
    NotFound:
      description: Resource not found
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error: Resource not found
            code: NOT_FOUND
            details: The requested resource could not be found
    Unauthorized:
      description: Authentication required
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error: Authentication required
            code: UNAUTHORIZED
            details: Valid authentication credentials are required
    Forbidden:
      description: Access denied
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error: Access denied
            code: FORBIDDEN
            details: Insufficient permissions for this action
    FeatureNotAllowed:
      description: App role feature permission denied
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/FeatureNotAllowedError'
          example:
            success: false
            error: feature_not_allowed
            resource: messaging
            action: email
            message: Your role does not have permission to send email for this project.
    BadRequest:
      description: Bad request
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error: Validation failed
            code: VALIDATION_ERROR
            details:
              email: Email is required
              password: Password must be at least 8 characters
    PayloadTooLarge:
      description: File or request body exceeds plan single-upload limit (or platform ceiling)
      content:
        application/json:
          schema:
            type: object
            properties:
              error:
                type: string
              maxFileUploadBytes:
                type: integer
                format: int64
          example:
            error: File size exceeds limit of 52428800 bytes
            maxFileUploadBytes: 52428800
    Conflict:
      description: Resource conflict
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error: Resource already exists
            code: CONFLICT
            details: A resource with this identifier already exists
    TooManyRequests:
      description: Rate limit exceeded
      content:
        application/json:
          schema:
            allOf:
              - $ref: '#/components/schemas/Error'
              - type: object
                properties:
                  retryAfter:
                    type: integer
          example:
            error: Rate limit exceeded
            code: RATE_LIMITED
            details: Too many requests. Try again in 60 seconds
            retryAfter: 60
    InternalServerError:
      description: Internal server error
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error: Internal server error
            code: INTERNAL_ERROR
            details: An unexpected error occurred
    ServiceUnavailable:
      description: >
        Service temporarily unavailable. Returned when the organization is restricted (e.g. suspended due to unpaid
        overage,

        spend limit exceeded, or API usage limit reached). End-users see a generic message; the real reason is logged
        server-side only.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error: Service temporarily unavailable. Please try again later.
            code: SERVICE_UNAVAILABLE
  examples:
    UserExample:
      value:
        _id: 685acbe0e129932fbb7a0fc2
        email: john.doe@mudbase.dev
        firstName: John
        lastName: Doe
        role: owner
        emailVerified: true
        twoFactorEnabled: false
        org:
          _id: 685acbe0e129932fbb7a0fc3
          name: Mudbase
          slug: mudbase
        createdAt: '2024-01-15T10:00:00.000Z'
        updatedAt: '2024-01-15T10:00:00.000Z'
    ProjectExample:
      value:
        _id: 65f1a2b3c4d5e6f7a8b9c0d1
        name: Mudbase Platform
        description: Main platform for Mudbase services
        slug: mudbase-platform
        org: 685acbe0e129932fbb7a0fc3
        apiKey: pk_live_abc123xyz789
        createdAt: '2024-01-15T10:00:00.000Z'
        updatedAt: '2024-01-15T10:00:00.000Z'
    CollectionExample:
      value:
        _id: 74a2b3c4d5e6f7a8b9c0d1e2
        name: users
        slug: users
        project: 65f1a2b3c4d5e6f7a8b9c0d1
        fields:
          - name: email
            type: email
            required: true
            unique: true
          - name: firstName
            type: string
            required: true
          - name: lastName
            type: string
            required: true
          - name: role
            type: string
            enum:
              - developer
              - admin
              - viewer
            default: developer
        createdAt: '2024-01-15T10:00:00.000Z'
        updatedAt: '2024-01-15T10:00:00.000Z'
    SmsByoPatchTwilio:
      summary: Twilio BYO
      description: |
        Twilio REST API credentials from the Twilio Console. `defaultFrom` should be a Twilio number or approved sender.
      value:
        enabled: true
        provider: twilio
        defaultFrom: '+15551234567'
        config:
          accountSid: ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
          authToken: your_auth_token
    SmsByoPatchTermii:
      summary: Termii BYO
      description: >
        API key from the Termii dashboard (Nigeria API host `api.ng.termii.com`). Optional `from` is used when the send
        call does not override the sender.
      value:
        enabled: true
        provider: termii
        defaultFrom: YourBrand
        config:
          apiKey: your_termii_api_key
          from: YourBrand
    SmsByoPatchAfricasTalking:
      summary: Africa's Talking BYO
      description: >
        Application username and API key from the Africa's Talking portal. Use the sandbox username for testing when
        applicable.
      value:
        enabled: true
        provider: africastalking
        defaultFrom: Mudbase
        config:
          username: sandbox
          apiKey: your_africastalking_api_key
    SmsByoPatchDisable:
      summary: Disable BYO SMS
      description: Turn off project BYO SMS; falls back to the platform SMS provider when sending SMS, if configured.
      value:
        enabled: false
        provider: none
    SmsByoGetTwilio:
      summary: Twilio configured (masked)
      value:
        success: true
        data:
          enabled: true
          provider: twilio
          defaultFrom: '+15551234567'
          hasCredentials: true
    SmsByoGetTermii:
      summary: Termii configured (masked)
      value:
        success: true
        data:
          enabled: true
          provider: termii
          defaultFrom: YourBrand
          hasCredentials: true
    SmsByoGetAfricasTalking:
      summary: Africa's Talking configured (masked)
      value:
        success: true
        data:
          enabled: true
          provider: africastalking
          defaultFrom: Mudbase
          hasCredentials: true
    SmsByoGetNone:
      summary: BYO SMS off or not set
      value:
        success: true
        data:
          enabled: false
          provider: none
          defaultFrom: ''
          hasCredentials: false
