{
  "openapi": "3.1.0",
  "info": {
    "title": "Coloring Book API",
    "version": "1.0.0",
    "description": "Internal API reference for the Coloring Book PDF Generator."
  },
  "servers": [
    {
      "url": "/",
      "description": "Current environment"
    }
  ],
  "paths": {
    "/api/auth/{nextauth}": {
      "get": {
        "tags": ["Auth"],
        "summary": "NextAuth.js handler (GET)",
        "description": "Handles NextAuth.js authentication flows — session retrieval, CSRF token, provider sign-in pages, callbacks.",
        "parameters": [
          {
            "name": "nextauth",
            "in": "path",
            "required": true,
            "schema": { "type": "string" },
            "description": "NextAuth.js catch-all path segment (e.g. session, csrf, signin, callback/google)."
          }
        ],
        "responses": {
          "200": { "description": "Varies by NextAuth.js action." }
        }
      },
      "post": {
        "tags": ["Auth"],
        "summary": "NextAuth.js handler (POST)",
        "description": "Handles NextAuth.js authentication flows — sign-in, sign-out, credential submission.",
        "parameters": [
          {
            "name": "nextauth",
            "in": "path",
            "required": true,
            "schema": { "type": "string" },
            "description": "NextAuth.js catch-all path segment."
          }
        ],
        "responses": {
          "200": { "description": "Varies by NextAuth.js action." }
        }
      }
    },
    "/api/generate": {
      "post": {
        "tags": ["Image Generation"],
        "summary": "Create image generation job",
        "description": "Creates an async image generation job. Deducts tokens upfront, validates prompt and page ownership, then queues an SQS message for the Lambda worker. Requires authentication.",
        "security": [{ "session": [] }],
        "responses": {
          "200": { "description": "Job created. Returns job ID." },
          "400": { "description": "Invalid request (missing prompt, page not found, etc.)." },
          "401": { "description": "Not authenticated." },
          "402": { "description": "Insufficient tokens." }
        }
      }
    },
    "/api/generate/jobs": {
      "get": {
        "tags": ["Image Generation"],
        "summary": "Batch query job statuses",
        "description": "Retrieves the status of multiple image generation jobs by their IDs. Used for polling. Requires authentication.",
        "security": [{ "session": [] }],
        "parameters": [
          {
            "name": "ids",
            "in": "query",
            "required": true,
            "schema": { "type": "string" },
            "description": "Comma-separated list of job IDs."
          }
        ],
        "responses": {
          "200": { "description": "Array of job status objects." },
          "401": { "description": "Not authenticated." }
        }
      }
    },
    "/api/generate/{jobId}": {
      "get": {
        "tags": ["Image Generation"],
        "summary": "Get single job status",
        "description": "Retrieves the status and details of a single image generation job. Requires authentication.",
        "security": [{ "session": [] }],
        "parameters": [
          {
            "name": "jobId",
            "in": "path",
            "required": true,
            "schema": { "type": "string" },
            "description": "The image generation job ID."
          }
        ],
        "responses": {
          "200": { "description": "Job status and details." },
          "401": { "description": "Not authenticated." },
          "404": { "description": "Job not found." }
        }
      }
    },
    "/api/prompt": {
      "post": {
        "tags": ["Prompts"],
        "summary": "Generate or improve a prompt",
        "description": "Generates a random coloring page prompt or improves an existing one using GPT-5.2. Requires authentication.",
        "security": [{ "session": [] }],
        "responses": {
          "200": { "description": "Generated or improved prompt text." },
          "401": { "description": "Not authenticated." }
        }
      }
    },
    "/api/prompt/batch": {
      "post": {
        "tags": ["Prompts"],
        "summary": "Generate batch of prompts",
        "description": "Generates a batch of prompts with titles for a full coloring book using generateBatchPrompts. Requires authentication.",
        "security": [{ "session": [] }],
        "responses": {
          "200": { "description": "Array of prompt objects with titles." },
          "401": { "description": "Not authenticated." }
        }
      }
    },
    "/api/coloring-books": {
      "get": {
        "tags": ["Coloring Books"],
        "summary": "List user's coloring books",
        "description": "Returns all coloring books belonging to the authenticated user. Requires authentication.",
        "security": [{ "session": [] }],
        "responses": {
          "200": { "description": "Array of coloring book objects." },
          "401": { "description": "Not authenticated." }
        }
      },
      "post": {
        "tags": ["Coloring Books"],
        "summary": "Create a coloring book",
        "description": "Creates a new coloring book for the authenticated user. Requires authentication.",
        "security": [{ "session": [] }],
        "responses": {
          "201": { "description": "Created coloring book." },
          "401": { "description": "Not authenticated." }
        }
      }
    },
    "/api/coloring-books/{id}": {
      "get": {
        "tags": ["Coloring Books"],
        "summary": "Get a coloring book",
        "description": "Retrieves a single coloring book by ID. Checks ownership. Requires authentication. Each page may include referenceImages; a missing field and an empty array both mean no page reference images, and book reference images still apply.",
        "security": [{ "session": [] }],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          }
        ],
        "responses": {
          "200": { "description": "Coloring book object with pages." },
          "401": { "description": "Not authenticated." },
          "403": { "description": "Not the owner." },
          "404": { "description": "Not found." }
        }
      },
      "patch": {
        "tags": ["Coloring Books"],
        "summary": "Update a coloring book",
        "description": "Book patch actions (discriminated by `action`). Includes book settings, add/remove pages, `updatePage` (prompt and cover metadata), `reorderPages`, `regenerateAll`, and `setPageLocks` (set `locked` on one or more pages by id). Page objects may include optional `locked`; when true, the server blocks AI generation, prompt/cover edits, image replace, and page reference image changes until unlocked.",
        "security": [{ "session": [] }],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "oneOf": [
                  {
                    "type": "object",
                    "required": ["action"],
                    "properties": {
                      "action": { "const": "setPageLocks" },
                      "pageIds": {
                        "type": "array",
                        "items": { "type": "string" },
                        "minItems": 1
                      },
                      "locked": { "type": "boolean" }
                    },
                    "additionalProperties": true
                  },
                  {
                    "type": "object",
                    "required": ["action"],
                    "properties": {
                      "action": { "type": "string" }
                    },
                    "additionalProperties": true
                  }
                ]
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Updated coloring book." },
          "401": { "description": "Not authenticated." },
          "403": { "description": "Not the owner." },
          "404": { "description": "Not found." }
        }
      },
      "delete": {
        "tags": ["Coloring Books"],
        "summary": "Delete a coloring book",
        "description": "Deletes a coloring book and its associated S3 assets. Checks ownership. Requires authentication.",
        "security": [{ "session": [] }],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          }
        ],
        "responses": {
          "200": { "description": "Book deleted." },
          "401": { "description": "Not authenticated." },
          "403": { "description": "Not the owner." },
          "404": { "description": "Not found." }
        }
      }
    },
    "/api/coloring-books/{id}/reference-images/presign": {
      "post": {
        "tags": ["Coloring Books"],
        "summary": "Presign book reference image uploads",
        "description": "Returns presigned S3 PUT URLs for staging book reference images. At most 14 images per book; the request is limited by remaining slots. Requires an authenticated owner.",
        "security": [{ "session": [] }],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          }
        ],
        "responses": {
          "200": { "description": "Upload session with presigned PUT URLs and remaining slots." },
          "400": { "description": "Invalid request or no remaining reference slots." },
          "401": { "description": "Not authenticated." },
          "403": { "description": "Not the owner." },
          "404": { "description": "Not found." }
        }
      }
    },
    "/api/coloring-books/{id}/reference-images/complete": {
      "post": {
        "tags": ["Coloring Books"],
        "summary": "Complete book reference image uploads",
        "description": "Processes staged uploads and appends them to the book's reference images (max 14). The batch is all-or-nothing. Requires an authenticated owner.",
        "security": [{ "session": [] }],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          }
        ],
        "responses": {
          "200": { "description": "Updated book with uploadedCount and failures." },
          "400": {
            "description": "Invalid request, no remaining slots, or a processing failure (uploadedCount 0)."
          },
          "401": { "description": "Not authenticated." },
          "403": { "description": "Not the owner." },
          "404": { "description": "Not found." }
        }
      }
    },
    "/api/coloring-books/{id}/reference-images/reorder": {
      "patch": {
        "tags": ["Coloring Books"],
        "summary": "Reorder book reference images",
        "description": "Reorders the book's reference images. orderedIds must list every current reference id exactly once. Requires an authenticated owner.",
        "security": [{ "session": [] }],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          }
        ],
        "responses": {
          "200": { "description": "Updated coloring book." },
          "400": { "description": "Invalid reorder request." },
          "401": { "description": "Not authenticated." },
          "403": { "description": "Not the owner." },
          "404": { "description": "Not found." }
        }
      }
    },
    "/api/coloring-books/{id}/reference-images/{refId}": {
      "delete": {
        "tags": ["Coloring Books"],
        "summary": "Delete a book reference image",
        "description": "Removes one reference image from book metadata. The S3 object is kept until the book is deleted. Requires an authenticated owner.",
        "security": [{ "session": [] }],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          },
          {
            "name": "refId",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          }
        ],
        "responses": {
          "200": { "description": "Updated coloring book." },
          "400": { "description": "Invalid reference id." },
          "401": { "description": "Not authenticated." },
          "403": { "description": "Not the owner." },
          "404": { "description": "Book or reference image not found." }
        }
      }
    },
    "/api/coloring-books/{id}/pages/{pageId}/reference-images/presign": {
      "post": {
        "tags": ["Coloring Books"],
        "summary": "Presign page reference image uploads",
        "description": "Returns presigned S3 PUT URLs for staging reference images on one page. Slot check counts that page's referenceImages only (max 14). Book images are sent before page images, up to the selected model limit (14, or 3 for xAI). A missing page is 404. Requires an authenticated owner.",
        "security": [{ "session": [] }],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          },
          {
            "name": "pageId",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          }
        ],
        "responses": {
          "200": {
            "description": "Upload session with presigned PUT URLs and remaining page slots."
          },
          "400": { "description": "Invalid request or no remaining page reference slots." },
          "401": { "description": "Not authenticated." },
          "403": { "description": "Not the owner." },
          "404": { "description": "Book or page not found." }
        }
      }
    },
    "/api/coloring-books/{id}/pages/{pageId}/reference-images/complete": {
      "post": {
        "tags": ["Coloring Books"],
        "summary": "Complete page reference image uploads",
        "description": "Processes staged uploads and appends them to that page's referenceImages only (max 14). Book reference images are unchanged. Book images are sent before page images, up to the selected model limit (14, or 3 for xAI). The batch is all-or-nothing. A missing page is 404. Requires an authenticated owner.",
        "security": [{ "session": [] }],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          },
          {
            "name": "pageId",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          }
        ],
        "responses": {
          "200": { "description": "Updated book with uploadedCount and failures." },
          "400": {
            "description": "Invalid request, no remaining page slots, or a processing failure (uploadedCount 0)."
          },
          "401": { "description": "Not authenticated." },
          "403": { "description": "Not the owner." },
          "404": { "description": "Book or page not found." }
        }
      }
    },
    "/api/coloring-books/{id}/pages/{pageId}/reference-images/reorder": {
      "patch": {
        "tags": ["Coloring Books"],
        "summary": "Reorder page reference images",
        "description": "Reorders that page's reference images. orderedIds must list every current page reference id exactly once. Book images are sent before page images, up to the selected model limit (14, or 3 for xAI). A missing page is 404. Requires an authenticated owner.",
        "security": [{ "session": [] }],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          },
          {
            "name": "pageId",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          }
        ],
        "responses": {
          "200": { "description": "Updated coloring book." },
          "400": { "description": "Invalid reorder request." },
          "401": { "description": "Not authenticated." },
          "403": { "description": "Not the owner." },
          "404": { "description": "Book or page not found." }
        }
      }
    },
    "/api/coloring-books/{id}/pages/{pageId}/reference-images/{refId}": {
      "delete": {
        "tags": ["Coloring Books"],
        "summary": "Delete a page reference image",
        "description": "Removes one reference image from that page. Book reference images are unchanged. Book images are sent before page images, up to the selected model limit (14, or 3 for xAI). A missing page or reference is 404. Requires an authenticated owner.",
        "security": [{ "session": [] }],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          },
          {
            "name": "pageId",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          },
          {
            "name": "refId",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          }
        ],
        "responses": {
          "200": { "description": "Updated coloring book." },
          "400": { "description": "Invalid reference id." },
          "401": { "description": "Not authenticated." },
          "403": { "description": "Not the owner." },
          "404": { "description": "Book, page, or reference image not found." }
        }
      }
    },
    "/api/coloring-books/{id}/pages/{pageId}/clone": {
      "post": {
        "tags": ["Coloring Books"],
        "summary": "Clone a page",
        "description": "Duplicates one coloring page in the same book and inserts the copy immediately after the source. Uploaded coloring pages can be cloned. Front and back covers cannot. A page with generation in progress cannot. The page image is copied to a new object key so the original file stays in place. Page reference images are copied under the new page id. A book cannot exceed 100 pages. No request body. Requires an authenticated owner.",
        "security": [{ "session": [] }],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          },
          {
            "name": "pageId",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          }
        ],
        "responses": {
          "200": {
            "description": "Updated book and the cloned page. The cloned page s3Key is a new object, not the source key."
          },
          "400": {
            "description": "Book is already at the page limit, the page is a front or back cover, or generation is still in progress."
          },
          "401": { "description": "Not authenticated." },
          "403": { "description": "Not the owner." },
          "404": { "description": "Book or page not found." }
        }
      }
    },
    "/api/coloring-books/{id}/pages/{pageId}/copy": {
      "post": {
        "tags": ["Coloring Books"],
        "summary": "Copy a page into another book",
        "description": "Copies one coloring page into another book owned by the same user. Uploaded coloring pages are copied. Front and back covers cannot. The page image is copied in storage. Book-level references are reused when the file bytes match, even if the names differ. The same name with different bytes returns 409 and writes nothing until referenceChoices is sent. Per-page references are copied onto the new page as new objects. A different page layout (vertical, horizontal, or square) marks the page needsRegeneration. Prompt history is not copied. Requires an authenticated owner of both books.",
        "security": [{ "session": [] }],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          },
          {
            "name": "pageId",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["targetBookId"],
                "properties": {
                  "targetBookId": { "type": "string" },
                  "referenceChoices": {
                    "type": "array",
                    "items": {
                      "type": "object",
                      "required": ["sourceRefId", "action"],
                      "properties": {
                        "sourceRefId": { "type": "string" },
                        "action": { "type": "string", "enum": ["reuse", "duplicate"] },
                        "targetRefId": { "type": "string" }
                      }
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Target book and the new page." },
          "400": {
            "description": "Invalid request, cover page, book is full, or no reference slot remains."
          },
          "401": { "description": "Not authenticated." },
          "403": { "description": "Caller does not own the source or target book." },
          "404": { "description": "Book or page not found." },
          "409": {
            "description": "Reference images partly match. Nothing was written. Send referenceChoices."
          }
        }
      }
    },
    "/api/coloring-books/{id}/pending-jobs": {
      "get": {
        "tags": ["Coloring Books"],
        "summary": "Get pending jobs for a book",
        "description": "Returns pending image generation jobs for pages in a coloring book. Used for editor polling. Requires authentication.",
        "security": [{ "session": [] }],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          }
        ],
        "responses": {
          "200": { "description": "Array of pending job objects." },
          "401": { "description": "Not authenticated." }
        }
      }
    },
    "/api/pdf/generate": {
      "post": {
        "tags": ["PDF"],
        "summary": "Generate PDF from coloring book",
        "description": "Generates a PDF from a coloring book, uploads it to S3, and returns a public URL. Requires authentication.",
        "security": [{ "session": [] }],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["bookId"],
                "properties": {
                  "bookId": {
                    "type": "string",
                    "description": "ID of the coloring book to generate a PDF from."
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Object with PDF URL and S3 key." },
          "400": { "description": "Invalid request (missing or invalid bookId)." },
          "401": { "description": "Not authenticated." },
          "403": { "description": "Not the book owner." }
        }
      }
    },
    "/api/pdf/download": {
      "get": {
        "tags": ["PDF"],
        "summary": "Get PDF download URL",
        "description": "Generates a signed S3 download URL for a PDF with 1-hour expiry. Requires authentication.",
        "security": [{ "session": [] }],
        "parameters": [
          {
            "name": "key",
            "in": "query",
            "required": true,
            "schema": { "type": "string" },
            "description": "S3 key of the PDF."
          }
        ],
        "responses": {
          "200": { "description": "Signed download URL." },
          "401": { "description": "Not authenticated." }
        }
      }
    },
    "/api/tokens/balance": {
      "get": {
        "tags": ["Tokens"],
        "summary": "Get token balance",
        "description": "Retrieves the current user's token balance. Requires authentication.",
        "security": [{ "session": [] }],
        "responses": {
          "200": { "description": "Object with balance field." },
          "401": { "description": "Not authenticated." }
        }
      }
    },
    "/api/stripe/create-checkout-session": {
      "post": {
        "tags": ["Payments"],
        "summary": "Create a Stripe-hosted Checkout Session",
        "description": "Creates a Checkout Session for a token package (0% VAT) and returns the hosted Checkout URL. Requires authentication.",
        "security": [{ "session": [] }],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["packageId"],
                "properties": {
                  "packageId": {
                    "type": "integer",
                    "minimum": 0,
                    "maximum": 2,
                    "description": "Token package index (0–2)."
                  },
                  "locale": {
                    "type": "string",
                    "enum": ["en", "de", "nl", "it", "es", "fr"],
                    "description": "Checkout UI locale."
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Object with hosted Checkout url." },
          "401": { "description": "Not authenticated." },
          "400": { "description": "Invalid package or Stripe error." }
        }
      }
    },
    "/api/stripe/checkout-session": {
      "get": {
        "tags": ["Payments"],
        "summary": "Confirm a Checkout Session for the thank-you page",
        "description": "Returns paid/pending/failed/expired for the signed-in buyer's session. Does not credit tokens. Requires authentication.",
        "security": [{ "session": [] }],
        "parameters": [
          {
            "name": "session_id",
            "in": "query",
            "required": true,
            "schema": { "type": "string", "pattern": "^cs_" },
            "description": "Stripe Checkout Session id."
          }
        ],
        "responses": {
          "200": { "description": "Object with state and tokens." },
          "401": { "description": "Not authenticated." },
          "404": { "description": "Session not found or not owned by the user." }
        }
      }
    },
    "/api/stripe/webhook": {
      "post": {
        "tags": ["Payments"],
        "summary": "Stripe webhook handler",
        "description": "Receives Stripe webhook events (payment_intent.succeeded, checkout.session.completed, checkout.session.async_payment_succeeded). Validates signature, credits tokens to user. No authentication — uses Stripe webhook secret for verification.",
        "responses": {
          "200": { "description": "Event processed." },
          "400": { "description": "Invalid signature or payload." }
        }
      }
    },
    "/api/account/orders": {
      "get": {
        "tags": ["Account"],
        "summary": "Get order history",
        "description": "Retrieves the user's Stripe payment orders/transactions. Requires authentication.",
        "security": [{ "session": [] }],
        "responses": {
          "200": { "description": "Array of order objects." },
          "401": { "description": "Not authenticated." }
        }
      }
    },
    "/api/account/token-usage": {
      "get": {
        "tags": ["Account"],
        "summary": "Get token usage breakdown",
        "description": "Returns token usage breakdown by coloring book project. Requires authentication.",
        "security": [{ "session": [] }],
        "responses": {
          "200": { "description": "Usage breakdown per project." },
          "401": { "description": "Not authenticated." }
        }
      }
    },
    "/api/account/history/pdf": {
      "get": {
        "tags": ["Account"],
        "summary": "Download history as PDF",
        "description": "Generates a downloadable PDF report of orders or token usage history. Requires authentication.",
        "security": [{ "session": [] }],
        "parameters": [
          {
            "name": "type",
            "in": "query",
            "required": true,
            "schema": { "type": "string", "enum": ["orders", "token-usage"] },
            "description": "Report type."
          }
        ],
        "responses": {
          "200": { "description": "PDF binary stream." },
          "401": { "description": "Not authenticated." }
        }
      }
    },
    "/api/admin/invoices": {
      "get": {
        "tags": ["Admin"],
        "summary": "List all invoices",
        "description": "Lists finalized invoices across all users (excludes PENDING placeholders). Same data as the admin Invoices tab. Requires an admin session or `x-admin-api-key` / `Authorization: Bearer` with `ADMIN_API_KEY`.",
        "security": [{ "session": [] }, { "adminApiKey": [] }],
        "responses": {
          "200": {
            "description": "Invoice summaries with user email, amount, and country code when known."
          },
          "401": { "description": "Not authenticated." },
          "403": { "description": "Not an admin." },
          "503": { "description": "Admin API key not configured on the server." }
        }
      }
    },
    "/api/admin/invoices/{invoiceId}/download": {
      "get": {
        "tags": ["Admin"],
        "summary": "Download invoice PDF by id",
        "description": "Streams the invoice PDF for any user. Requires admin session or admin API key (full admin, not invoice-only). Invoice-only bots should use the coloring-book-ai-agent IAM user instead.",
        "security": [{ "session": [] }, { "adminApiKey": [] }],
        "parameters": [
          {
            "name": "invoiceId",
            "in": "path",
            "required": true,
            "schema": { "type": "string", "pattern": "^inv_" },
            "description": "Invoice id (e.g. inv_txn_pi_…)."
          }
        ],
        "responses": {
          "200": { "description": "PDF binary stream." },
          "401": { "description": "Not authenticated." },
          "403": { "description": "Not an admin." },
          "404": { "description": "Invoice or PDF not found." },
          "409": { "description": "Invoice still generating." }
        }
      }
    },
    "/api/admin/users/{id}/invoices/{invoiceId}/download": {
      "get": {
        "tags": ["Admin"],
        "summary": "Download invoice PDF for user",
        "description": "Same PDF as `/api/admin/invoices/{invoiceId}/download` but requires the invoice to belong to `{id}`. Requires admin session or admin API key.",
        "security": [{ "session": [] }, { "adminApiKey": [] }],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          },
          {
            "name": "invoiceId",
            "in": "path",
            "required": true,
            "schema": { "type": "string", "pattern": "^inv_" }
          }
        ],
        "responses": {
          "200": { "description": "PDF binary stream." },
          "401": { "description": "Not authenticated." },
          "403": { "description": "Not an admin or invoice belongs to another user." },
          "404": { "description": "Invoice or PDF not found." },
          "409": { "description": "Invoice still generating." }
        }
      }
    },
    "/api/admin/users": {
      "get": {
        "tags": ["Admin"],
        "summary": "List all users",
        "description": "Lists all registered users with project counts and token balances. Requires admin role.",
        "security": [{ "session": [] }, { "adminApiKey": [] }],
        "responses": {
          "200": { "description": "Array of admin user objects." },
          "401": { "description": "Not authenticated." },
          "403": { "description": "Not an admin." }
        }
      }
    },
    "/api/admin/users/{id}": {
      "delete": {
        "tags": ["Admin"],
        "summary": "Delete a user",
        "description": "Deletes a user and all their coloring books. Prevents self-deletion and deletion of other admins. Requires admin role.",
        "security": [{ "session": [] }],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          }
        ],
        "responses": {
          "200": { "description": "User deleted." },
          "400": { "description": "Cannot delete self or other admins." },
          "401": { "description": "Not authenticated." },
          "403": { "description": "Not an admin." }
        }
      }
    },
    "/api/admin/users/{id}/grant-tokens": {
      "post": {
        "tags": ["Admin"],
        "summary": "Grant tokens to user",
        "description": "Grants tokens to a user via admin grant transaction. Requires admin role.",
        "security": [{ "session": [] }],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          }
        ],
        "responses": {
          "200": { "description": "Tokens granted. Returns new balance." },
          "400": { "description": "Invalid amount." },
          "401": { "description": "Not authenticated." },
          "403": { "description": "Not an admin." }
        }
      }
    },
    "/api/admin/trigger-sample": {
      "post": {
        "tags": ["Admin"],
        "summary": "Trigger sample PDF generation",
        "description": "Starts a single batch Step Functions execution for sample PDFs. Supports top-level defaults and per-config overrides. If `configs` is omitted or empty, all active age ranges are generated with defaults. Requires admin role.",
        "security": [{ "session": [] }],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "week": {
                    "type": "string",
                    "description": "Optional default week identifier (e.g. 2026-W19). If omitted, current week is used."
                  },
                  "pageCount": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": 20,
                    "default": 3,
                    "description": "Default page count for all configs (1–50, defaults to 3)."
                  },
                  "quality": {
                    "type": "string",
                    "enum": ["low", "medium", "high"],
                    "description": "Optional batch-wide image quality override for all configs. When omitted at both top-level and per-config, age-group defaults apply: kids-simple (2–5) low, kids-medium (6–9) medium, kids-detailed (10–12) high, adult-relaxed medium, adult-detailed high."
                  },
                  "topicSeed": {
                    "type": "string",
                    "minLength": 1,
                    "maxLength": 500,
                    "description": "Optional shared topic phrase for every age group in the batch. When set, skips topic round-robin and reuses this theme for every config. Omit it to fall back to one shared round-robin topic."
                  },
                  "configs": {
                    "type": "array",
                    "description": "Optional per-sample configs. Empty or omitted means generate all active age ranges with defaults.",
                    "items": {
                      "type": "object",
                      "required": ["ageRange"],
                      "properties": {
                        "ageRange": {
                          "type": "string",
                          "enum": [
                            "kids-simple",
                            "kids-medium",
                            "kids-detailed",
                            "adult-relaxed",
                            "adult-detailed"
                          ]
                        },
                        "week": {
                          "type": "string",
                          "description": "Optional per-config week override."
                        },
                        "pageCount": {
                          "type": "integer",
                          "minimum": 1,
                          "maximum": 20,
                          "description": "Optional per-config page count override."
                        },
                        "quality": {
                          "type": "string",
                          "enum": ["low", "medium", "high"],
                          "description": "Optional per-config image quality override. When omitted, uses top-level quality if set, otherwise the age-group default."
                        }
                      }
                    }
                  }
                }
              },
              "examples": {
                "qualityByAgeGroup": {
                  "summary": "Weekly sample quality per age group",
                  "value": {
                    "week": "2026-W19",
                    "pageCount": 3,
                    "configs": [
                      { "ageRange": "kids-simple", "quality": "low" },
                      { "ageRange": "kids-medium", "quality": "medium" },
                      { "ageRange": "kids-detailed", "quality": "high" },
                      { "ageRange": "adult-relaxed", "quality": "medium" },
                      { "ageRange": "adult-detailed", "quality": "high" }
                    ]
                  }
                },
                "fullyConfiguredBatch": {
                  "summary": "Fully configured batch with per-config overrides",
                  "value": {
                    "week": "2026-W19",
                    "pageCount": 4,
                    "quality": "high",
                    "configs": [
                      {
                        "ageRange": "kids-simple",
                        "week": "2026-W20",
                        "pageCount": 3,
                        "quality": "low"
                      },
                      {
                        "ageRange": "kids-medium",
                        "pageCount": 4,
                        "quality": "medium"
                      },
                      {
                        "ageRange": "kids-detailed",
                        "pageCount": 5,
                        "quality": "high"
                      },
                      {
                        "ageRange": "adult-relaxed",
                        "pageCount": 3,
                        "quality": "medium"
                      },
                      {
                        "ageRange": "adult-detailed",
                        "week": "2026-W19",
                        "pageCount": 6,
                        "quality": "high"
                      }
                    ]
                  }
                },
                "useDefaultsForAllActiveAges": {
                  "summary": "Generate all active age ranges with per-age quality defaults",
                  "value": {
                    "week": "2026-W19",
                    "pageCount": 3,
                    "configs": []
                  }
                },
                "minimalPayloadAllDefaults": {
                  "summary": "Minimal payload; current week, page count 3, and per-age quality defaults",
                  "value": {}
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Batch execution started. Returns execution metadata, resolved defaults, and resolved configs."
          },
          "401": { "description": "Not authenticated." },
          "403": { "description": "Not an admin." }
        }
      }
    },
    "/api/admin/maintenance/tables/{tableName}": {
      "get": {
        "tags": ["Admin"],
        "summary": "Browse DynamoDB table contents",
        "description": "Scans a DynamoDB table with cursor-based pagination. Returns raw items for debugging. Requires admin role.",
        "security": [{ "session": [] }],
        "parameters": [
          {
            "name": "tableName",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "enum": ["users", "coloring-books", "tokens-transactions", "image-jobs"]
            },
            "description": "Logical table name."
          },
          {
            "name": "limit",
            "in": "query",
            "schema": { "type": "integer", "default": 25, "minimum": 1, "maximum": 100 },
            "description": "Items per page."
          },
          {
            "name": "cursor",
            "in": "query",
            "schema": { "type": "string" },
            "description": "base64url-encoded LastEvaluatedKey from previous response."
          }
        ],
        "responses": {
          "200": { "description": "Paginated table items with nextCursor." },
          "401": { "description": "Not authenticated." },
          "403": { "description": "Not an admin." },
          "404": { "description": "Unknown table name." }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "session": {
        "type": "apiKey",
        "in": "cookie",
        "name": "authjs.session-token",
        "description": "NextAuth.js session cookie. Authenticate by signing in via the app."
      },
      "adminApiKey": {
        "type": "apiKey",
        "in": "header",
        "name": "x-admin-api-key",
        "description": "Static admin key (`ADMIN_API_KEY`). Alternative: `Authorization: Bearer <key>`. Used by Cursor Cloud Agents and local skills."
      }
    }
  },
  "tags": [
    { "name": "Auth", "description": "Authentication (NextAuth.js)" },
    { "name": "Coloring Books", "description": "CRUD operations for coloring books" },
    { "name": "Image Generation", "description": "Async image generation jobs" },
    { "name": "Prompts", "description": "AI prompt generation and improvement" },
    { "name": "PDF", "description": "PDF generation and download" },
    { "name": "Tokens", "description": "Token balance" },
    { "name": "Payments", "description": "Stripe payments and webhooks" },
    { "name": "Account", "description": "User account, orders, and usage history" },
    { "name": "Admin", "description": "Admin-only user management and maintenance" }
  ]
}
