openapi: '3.1.0'
info:
  title: Motionworks API - Platform (Markets, Segments, Auth, Billing)
  version: 2.0.0
  description: >
    Shared platform endpoints for markets, audience segments, authentication,
    billing, health checks, and search.
  contact:
    name: Motionworks AI
    url: https://mworks.com
    email: api@mworks.com

servers:
  - url: https://api.mworks.com/v2
    description: Production

components:
  securitySchemes:
    apiKey:
      type: apiKey
      name: X-API-Key
      in: header

  schemas:
    Market:
      type: object
      properties:
        market_id:
          type: string
        name:
          type: string
        dma_code:
          type: string
        population:
          type: integer
        households:
          type: integer
        spots_count:
          type: integer
        latitude:
          type: number
          format: double
        longitude:
          type: number
          format: double
        zoom:
          type: integer

    Segment:
      type: object
      properties:
        segment_id:
          type: string
        name:
          type: string
        description:
          type: string
        category:
          type: string
          enum: [Demographic, Behavioral, Lifestyle, Purchase Intent, Custom]
        universe_size:
          type: integer

    CreditBalance:
      type: object
      properties:
        org_id:
          type: string
        tier:
          type: string
          enum: [sandbox, growth, enterprise]
        credits_used:
          type: integer
        credits_remaining:
          type: integer
        credits_total:
          type: integer
        reset_at:
          type: string
          format: date-time

    HealthStatus:
      type: object
      properties:
        status:
          type: string
          enum: [healthy, degraded, down]
        version:
          type: string
        timestamp:
          type: string
          format: date-time

    DataFreshness:
      type: object
      properties:
        latest_measurement_period:
          type: string
          format: date
        profiles_updated_count:
          type: integer
        next_expected_refresh:
          type: string
          format: date
        data_sources:
          type: array
          items:
            type: object
            properties:
              name:
                type: string
              last_updated:
                type: string
                format: date-time
              status:
                type: string

    SignupRequest:
      type: object
      required: [email, company]
      properties:
        email:
          type: string
          format: email
        company:
          type: string
        use_case:
          type: string

    SignupResponse:
      type: object
      properties:
        org_id:
          type: string
        api_key:
          type: string
        tier:
          type: string
        credits_per_month:
          type: integer
        rate_limit:
          type: string
        dashboard_url:
          type: string

paths:
  /markets:
    get:
      operationId: listMarkets
      summary: List all DMA markets
      x-credit-cost: 1
      security:
        - apiKey: []
      parameters:
        - name: include_metrics
          in: query
          schema:
            type: boolean
            default: false
      responses:
        '200':
          description: Array of markets

  /markets/{id}:
    get:
      operationId: getMarket
      summary: Get market detail
      x-credit-cost: 1
      security:
        - apiKey: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Market detail
        '404':
          description: Market not found

  /segments:
    get:
      operationId: listSegments
      summary: List audience segments
      x-credit-cost: 1
      security:
        - apiKey: []
      responses:
        '200':
          description: Array of segments

  /segments/{id}:
    get:
      operationId: getSegment
      summary: Get segment detail
      x-credit-cost: 1
      security:
        - apiKey: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Segment detail
        '404':
          description: Segment not found

  /health:
    get:
      operationId: getHealth
      summary: API health check
      x-credit-cost: 0
      security: []
      responses:
        '200':
          description: Health status

  /health/data:
    get:
      operationId: getDataFreshness
      summary: Data freshness status
      x-credit-cost: 0
      security: []
      responses:
        '200':
          description: Data freshness info

  /signup:
    post:
      operationId: createAccount
      summary: Create sandbox account
      x-credit-cost: 0
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SignupRequest'
      responses:
        '201':
          description: Account created
        '409':
          description: Email already registered

  /billing/credits:
    get:
      operationId: getCreditBalance
      summary: Check credit balance
      x-credit-cost: 0
      security:
        - apiKey: []
      responses:
        '200':
          description: Credit balance

  /billing/checkout:
    post:
      operationId: createCheckoutSession
      summary: Create a Stripe Checkout subscription session
      description: |
        Creates a Stripe Checkout Session for a subscription on the configured
        professional-monthly price. Returns the hosted checkout URL inside a
        standard `{ data, meta }` envelope. No credits charged.
      x-credit-cost: 0
      x-motionworks-status: production
      security: []
      responses:
        '200':
          description: Checkout session created
          content:
            application/json:
              schema:
                type: object
                required: [data, meta]
                properties:
                  data:
                    type: object
                    properties:
                      url:
                        type: string
                        format: uri
                        description: Stripe Checkout hosted page URL
                  meta:
                    type: object
                    properties:
                      request_id:
                        type: string
                      credits_used:
                        type: integer
                      credits_remaining:
                        type: integer
                      product:
                        type: string
                      version:
                        type: string
                      provenance:
                        type: object
        '400':
          description: Stripe API error (passthrough)
        '500':
          description: Internal error during checkout-session creation
        '503':
          description: Stripe is not configured (missing key or price id)

  /billing/webhook:
    post:
      operationId: stripeWebhook
      summary: Stripe webhook receiver (signature-verified)
      description: |
        Receives Stripe webhook events. Verifies the `Stripe-Signature` header
        with constant-time HMAC-SHA256 against the raw body, with a 5-minute
        freshness window. Returns `{ received: true }` on success — the body
        is consumed by Stripe (which only reads the HTTP status), so this
        endpoint is exempt from the standard `{ data, meta }` envelope.
      x-credit-cost: 0
      x-motionworks-status: production
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
      parameters:
        - in: header
          name: stripe-signature
          required: true
          schema:
            type: string
          description: Stripe signature header (`t=<unix-ts>,v1=<hex-hmac>`)
      responses:
        '200':
          description: Event acknowledged
          content:
            application/json:
              schema:
                type: object
                properties:
                  received:
                    type: boolean
                    enum: [true]
        '400':
          description: Invalid signature, malformed signature, or unparseable JSON body
        '503':
          description: Webhook secret is not configured
