{
  "openapi": "3.1.0",
  "info": {
    "title": "CamOS API",
    "version": "1.0.0",
    "description": "CamOS는 2~10인 마케팅팀을 위한 캠페인 관리 SaaS(Threads 채널 우선)의 내부 API입니다. 대부분의 엔드포인트는 로그인 세션 쿠키(Auth.js)로 인증하는 멀티테넌트 API이며, 테넌트 사용자가 아닌 외부 승인자를 위한 토큰 기반 공개 엔드포인트(/api/public/approve/{token})도 일부 제공합니다. 이 문서는 사람 개발자보다 AI 에이전트/크롤러가 API 표면을 파악하도록 돕기 위해 공개되었습니다."
  },
  "servers": [{ "url": "https://camos-kr.vercel.app" }],
  "security": [{ "sessionCookie": [] }],
  "tags": [
    { "name": "Campaigns" },
    { "name": "Contents" },
    { "name": "Channels" },
    { "name": "Team" },
    { "name": "Subscription" },
    { "name": "Reports" },
    { "name": "OAuth" },
    { "name": "Public" }
  ],
  "paths": {
    "/api/campaigns": {
      "get": {
        "tags": ["Campaigns"],
        "summary": "캠페인 목록 조회",
        "description": "로그인한 사용자의 테넌트에 속한 캠페인 목록을 상태·검색어로 필터링해 조회합니다.",
        "parameters": [
          { "name": "status", "in": "query", "schema": { "type": "string", "enum": ["planning", "in_progress", "completed", "archived"] } },
          { "name": "q", "in": "query", "schema": { "type": "string" }, "description": "캠페인 이름 부분 검색어" }
        ],
        "responses": {
          "200": { "description": "성공", "content": { "application/json": { "schema": { "type": "object", "properties": { "campaigns": { "type": "array", "items": { "$ref": "#/components/schemas/Campaign" } } } } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" }
        }
      },
      "post": {
        "tags": ["Campaigns"],
        "summary": "캠페인 생성",
        "description": "이번 달 캠페인 생성 수가 구독 티어 한도 이내인 경우에만 생성됩니다.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["name", "defaultApproverId"],
                "properties": {
                  "name": { "type": "string", "minLength": 2, "maxLength": 100 },
                  "goal": { "type": "string", "maxLength": 3000, "description": "캠페인 주제/배경자료 — AI 초안 생성의 입력으로 사용" },
                  "startDate": { "type": "string", "format": "date-time" },
                  "endDate": { "type": "string", "format": "date-time" },
                  "defaultApproverId": { "type": "string", "format": "uuid" },
                  "channelCodes": { "type": "array", "items": { "type": "string" }, "minItems": 1, "default": ["threads"] }
                }
              }
            }
          }
        },
        "responses": {
          "201": { "description": "생성됨", "content": { "application/json": { "schema": { "type": "object", "properties": { "campaign": { "$ref": "#/components/schemas/Campaign" } } } } } },
          "400": { "$ref": "#/components/responses/ValidationError" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "402": { "description": "이번 달 캠페인 생성 한도 초과(TIER_LIMIT_EXCEEDED)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
        }
      }
    },
    "/api/campaigns/{id}": {
      "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } }],
      "get": {
        "tags": ["Campaigns"],
        "summary": "캠페인 상세 조회",
        "responses": {
          "200": { "description": "성공", "content": { "application/json": { "schema": { "type": "object", "properties": { "campaign": { "$ref": "#/components/schemas/Campaign" } } } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      },
      "patch": {
        "tags": ["Campaigns"],
        "summary": "캠페인 수정",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "name": { "type": "string", "minLength": 2, "maxLength": 100 },
                  "goal": { "type": "string", "maxLength": 3000 },
                  "status": { "type": "string", "enum": ["planning", "in_progress", "completed", "archived"] }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "성공", "content": { "application/json": { "schema": { "type": "object", "properties": { "campaign": { "$ref": "#/components/schemas/Campaign" } } } } } },
          "400": { "$ref": "#/components/responses/ValidationError" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      },
      "delete": {
        "tags": ["Campaigns"],
        "summary": "캠페인 삭제 (소프트 삭제, 테넌트 관리자 전용)",
        "responses": {
          "200": { "description": "성공", "content": { "application/json": { "schema": { "type": "object", "properties": { "success": { "type": "boolean" } } } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      }
    },
    "/api/campaigns/{id}/ai-draft-channels": {
      "post": {
        "tags": ["Campaigns"],
        "summary": "캠페인에 연결된 모든 채널에 대해 AI 초안 일괄 생성",
        "description": "캠페인 목표/키워드/톤과 첨부 자료를 바탕으로, 연결된 각 채널용 콘텐츠 초안을 생성합니다. 채널별로 독립 처리되어 일부가 실패해도 나머지는 계속 진행됩니다.",
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } }],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "keywords": { "type": "string", "maxLength": 300 },
                  "tone": { "type": "string", "maxLength": 100 }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "성공(부분 실패 가능)",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "created": { "type": "array", "items": { "type": "object", "properties": { "channelCode": { "type": "string" }, "channelName": { "type": "string" }, "contentId": { "type": "string", "format": "uuid" } } } },
                    "failed": { "type": "array", "items": { "type": "object", "properties": { "channelCode": { "type": "string" }, "channelName": { "type": "string" }, "message": { "type": "string" } } } }
                  }
                }
              }
            }
          },
          "400": { "$ref": "#/components/responses/ValidationError" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "402": { "description": "이번 달 AI 초안 생성 한도 초과", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "404": { "$ref": "#/components/responses/NotFound" },
          "500": { "description": "AI 제공자(Anthropic) 미설정", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
        }
      }
    },
    "/api/campaigns/{id}/attachments": {
      "post": {
        "tags": ["Campaigns"],
        "summary": "캠페인 첨부파일 업로드",
        "description": "AI 초안 생성 참고자료 및 Threads 이미지 자동 발행용 첨부파일을 업로드합니다. 이미지(jpeg/png/webp/gif) 또는 문서(.md/.txt)만 허용하며 최대 8MB입니다.",
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } }],
        "requestBody": {
          "required": true,
          "content": {
            "multipart/form-data": {
              "schema": { "type": "object", "required": ["file"], "properties": { "file": { "type": "string", "format": "binary" } } }
            }
          }
        },
        "responses": {
          "201": { "description": "업로드됨", "content": { "application/json": { "schema": { "type": "object", "properties": { "attachment": { "$ref": "#/components/schemas/Attachment" } } } } } },
          "400": { "$ref": "#/components/responses/ValidationError" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "502": { "description": "업로드 실패(Blob 저장소 오류)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
        }
      }
    },
    "/api/campaigns/{id}/attachments/{attachmentId}": {
      "delete": {
        "tags": ["Campaigns"],
        "summary": "캠페인 첨부파일 삭제",
        "parameters": [
          { "name": "id", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } },
          { "name": "attachmentId", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } }
        ],
        "responses": {
          "200": { "description": "성공", "content": { "application/json": { "schema": { "type": "object", "properties": { "success": { "type": "boolean" } } } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      }
    },
    "/api/contents": {
      "post": {
        "tags": ["Contents"],
        "summary": "콘텐츠(포스트) 생성",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["campaignId", "bodyText"],
                "properties": {
                  "campaignId": { "type": "string", "format": "uuid" },
                  "channelCode": { "type": "string", "description": "미지정 시 캠페인의 첫 번째 연결 채널 사용" },
                  "bodyText": { "type": "string", "minLength": 1, "maxLength": 5000 },
                  "aiGenerated": { "type": "boolean" }
                }
              }
            }
          }
        },
        "responses": {
          "201": { "description": "생성됨", "content": { "application/json": { "schema": { "type": "object", "properties": { "content": { "$ref": "#/components/schemas/Content" } } } } } },
          "400": { "$ref": "#/components/responses/ValidationError" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "description": "CAMPAIGN_NOT_FOUND" }
        }
      }
    },
    "/api/contents/{id}": {
      "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } }],
      "get": {
        "tags": ["Contents"],
        "summary": "콘텐츠 상세 조회 (버전 이력·컨펌 이력 포함)",
        "responses": {
          "200": { "description": "성공", "content": { "application/json": { "schema": { "type": "object", "properties": { "content": { "$ref": "#/components/schemas/Content" } } } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      },
      "patch": {
        "tags": ["Contents"],
        "summary": "콘텐츠 본문/예정일/첨부 이미지 수정",
        "description": "본문 수정 시마다 새 버전 이력이 추가됩니다. 작성중(draft) 상태에서만 본문/이미지를 수정할 수 있고, 발행 예정일은 발행완료 전이라면 상태와 무관하게 변경 가능합니다.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "bodyText": { "type": "string", "minLength": 1, "maxLength": 5000 },
                  "scheduledPublishAt": { "type": ["string", "null"], "format": "date-time" },
                  "imageUrl": { "type": ["string", "null"], "format": "uri" }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "성공", "content": { "application/json": { "schema": { "type": "object", "properties": { "content": { "$ref": "#/components/schemas/Content" } } } } } },
          "400": { "$ref": "#/components/responses/ValidationError" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "description": "INVALID_STATE — 수정 가능한 상태가 아님" }
        }
      }
    },
    "/api/contents/{id}/ai-draft": {
      "post": {
        "tags": ["Contents"],
        "summary": "콘텐츠 AI 초안 재생성 (A/B 2안 미리보기)",
        "description": "결과는 저장되지 않는 미리보기입니다. 실제 반영은 사용자가 PATCH /api/contents/{id}로 별도 적용합니다.",
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } }],
        "requestBody": {
          "content": { "application/json": { "schema": { "type": "object", "properties": { "keywords": { "type": "string", "maxLength": 300 }, "tone": { "type": "string", "maxLength": 100 } } } } }
        },
        "responses": {
          "200": { "description": "성공", "content": { "application/json": { "schema": { "type": "object", "properties": { "drafts": { "type": "array", "items": { "type": "object" } } } } } } },
          "400": { "$ref": "#/components/responses/ValidationError" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "402": { "description": "이번 달 AI 초안 생성 한도 초과" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "500": { "description": "AI 제공자 미설정" },
          "502": { "description": "AI 제공자 호출 실패" }
        }
      }
    },
    "/api/contents/{id}/approve": {
      "post": {
        "tags": ["Contents"],
        "summary": "콘텐츠 승인 (승인권자/테넌트 관리자 전용)",
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } }],
        "responses": {
          "200": { "description": "성공", "content": { "application/json": { "schema": { "type": "object", "properties": { "content": { "$ref": "#/components/schemas/Content" } } } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "description": "INVALID_STATE — 컨펌 대기 상태가 아님" }
        }
      }
    },
    "/api/contents/{id}/reject": {
      "post": {
        "tags": ["Contents"],
        "summary": "콘텐츠 반려 (승인권자/테넌트 관리자 전용)",
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } }],
        "requestBody": {
          "required": true,
          "content": { "application/json": { "schema": { "type": "object", "required": ["reason"], "properties": { "reason": { "type": "string", "minLength": 1, "maxLength": 1000 } } } } }
        },
        "responses": {
          "200": { "description": "성공", "content": { "application/json": { "schema": { "type": "object", "properties": { "content": { "$ref": "#/components/schemas/Content" } } } } } },
          "400": { "$ref": "#/components/responses/ValidationError" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      }
    },
    "/api/contents/{id}/request-approval": {
      "post": {
        "tags": ["Contents"],
        "summary": "컨펌 요청 상신",
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } }],
        "responses": {
          "200": { "description": "성공", "content": { "application/json": { "schema": { "type": "object", "properties": { "content": { "$ref": "#/components/schemas/Content" } } } } } },
          "400": { "description": "EMPTY_BODY" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "description": "INVALID_STATE — 작성중 상태가 아님" }
        }
      }
    },
    "/api/contents/{id}/duplicate": {
      "post": {
        "tags": ["Contents"],
        "summary": "콘텐츠 복제 (새 작성중 초안 생성)",
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } }],
        "responses": {
          "201": { "description": "생성됨", "content": { "application/json": { "schema": { "type": "object", "properties": { "content": { "$ref": "#/components/schemas/Content" } } } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      }
    },
    "/api/contents/{id}/external-approval-link": {
      "post": {
        "tags": ["Contents"],
        "summary": "로그인 없이 승인/반려 가능한 외부 공유 링크 발급",
        "description": "컨펌 대기 상태의 콘텐츠에 대해서만 발급됩니다. 발급된 토큰은 GET/POST /api/public/approve/{token}에서 사용됩니다.",
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } }],
        "responses": {
          "200": { "description": "성공", "content": { "application/json": { "schema": { "type": "object", "properties": { "url": { "type": "string", "format": "uri" } } } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "description": "INVALID_STATE — 컨펌 대기 상태가 아님" }
        }
      }
    },
    "/api/contents/{id}/performance": {
      "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } }],
      "get": {
        "tags": ["Contents"],
        "summary": "콘텐츠 성과 입력 이력 조회",
        "responses": {
          "200": { "description": "성공", "content": { "application/json": { "schema": { "type": "object", "properties": { "metrics": { "type": "array", "items": { "$ref": "#/components/schemas/PerformanceMetric" } } } } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" }
        }
      },
      "post": {
        "tags": ["Contents"],
        "summary": "성과 지표 수기 입력",
        "description": "발행완료 상태의 콘텐츠에만 입력할 수 있으며, 재입력 시마다 새 이력 행이 추가됩니다.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "views": { "type": "integer", "minimum": 0, "default": 0 },
                  "likes": { "type": "integer", "minimum": 0, "default": 0 },
                  "comments": { "type": "integer", "minimum": 0, "default": 0 },
                  "shares": { "type": "integer", "minimum": 0, "default": 0 }
                }
              }
            }
          }
        },
        "responses": {
          "201": { "description": "생성됨", "content": { "application/json": { "schema": { "type": "object", "properties": { "metric": { "$ref": "#/components/schemas/PerformanceMetric" } } } } } },
          "400": { "$ref": "#/components/responses/ValidationError" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "description": "INVALID_STATE — 발행완료 상태가 아님" }
        }
      }
    },
    "/api/contents/{id}/publish": {
      "post": {
        "tags": ["Contents"],
        "summary": "수동 발행 완료 처리",
        "description": "채널에 사람이 직접 게시한 뒤, 그 사실을 기록하는 용도입니다. 발행 대기(ready_to_publish) 상태에서만 가능합니다.",
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } }],
        "requestBody": {
          "content": { "application/json": { "schema": { "type": "object", "properties": { "publishedUrl": { "type": "string", "format": "uri" }, "publishedAt": { "type": "string", "format": "date-time" } } } } }
        },
        "responses": {
          "200": { "description": "성공", "content": { "application/json": { "schema": { "type": "object", "properties": { "content": { "$ref": "#/components/schemas/Content" } } } } } },
          "400": { "$ref": "#/components/responses/ValidationError" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "description": "INVALID_STATE — 발행 대기 상태가 아님" }
        }
      }
    },
    "/api/contents/{id}/publish-auto": {
      "post": {
        "tags": ["Contents"],
        "summary": "채널 API를 통한 자동 발행 (현재 Threads만 지원)",
        "description": "테넌트에 연결된 채널(Access Token)이 있어야 하며, 만료된 경우 재연결이 필요합니다.",
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } }],
        "responses": {
          "200": { "description": "성공", "content": { "application/json": { "schema": { "type": "object", "properties": { "content": { "$ref": "#/components/schemas/Content" } } } } } },
          "400": { "description": "CHANNEL_NOT_CONNECTED 또는 CHANNEL_TOKEN_EXPIRED" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "description": "INVALID_STATE — 발행 대기 상태가 아님" },
          "502": { "description": "PUBLISH_FAILED — 채널 API 호출 실패" }
        }
      }
    },
    "/api/channels/threads/inbox": {
      "get": {
        "tags": ["Channels"],
        "summary": "Threads 통합 인박스 — 최근 발행글 20건의 댓글 조회",
        "responses": {
          "200": { "description": "성공", "content": { "application/json": { "schema": { "type": "object", "properties": { "posts": { "type": "array", "items": { "type": "object" } } } } } } },
          "400": { "description": "CHANNEL_NOT_CONNECTED 또는 CHANNEL_TOKEN_EXPIRED" },
          "401": { "$ref": "#/components/responses/Unauthorized" }
        }
      }
    },
    "/api/channels/threads/inbox/reply": {
      "post": {
        "tags": ["Channels"],
        "summary": "인박스 댓글에 답장",
        "requestBody": {
          "required": true,
          "content": { "application/json": { "schema": { "type": "object", "required": ["replyToId", "text"], "properties": { "replyToId": { "type": "string" }, "text": { "type": "string", "minLength": 1, "maxLength": 500 } } } } }
        },
        "responses": {
          "200": { "description": "성공", "content": { "application/json": { "schema": { "type": "object", "properties": { "success": { "type": "boolean" } } } } } },
          "400": { "description": "VALIDATION_ERROR 또는 CHANNEL_NOT_CONNECTED" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "502": { "description": "REPLY_FAILED" }
        }
      }
    },
    "/api/channels/threads/disconnect": {
      "post": {
        "tags": ["Channels"],
        "summary": "Threads 채널 연결 해제 (테넌트 관리자 전용)",
        "responses": {
          "200": { "description": "성공", "content": { "application/json": { "schema": { "type": "object", "properties": { "success": { "type": "boolean" } } } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "403": { "$ref": "#/components/responses/Forbidden" }
        }
      }
    },
    "/api/channels/threads/refresh": {
      "get": {
        "tags": ["Channels"],
        "summary": "Threads 장기 토큰(60일) 자동 갱신 배치 (Vercel Cron 전용)",
        "description": "세션 쿠키가 아닌 `Authorization: Bearer <CRON_SECRET>` 헤더로 인증합니다. Vercel Cron이 매일 호출합니다(vercel.json 참고).",
        "security": [{ "cronSecret": [] }],
        "responses": {
          "200": { "description": "성공", "content": { "application/json": { "schema": { "type": "object", "properties": { "refreshed": { "type": "integer" }, "failed": { "type": "integer" } } } } } },
          "401": { "description": "UNAUTHORIZED — Cron secret 불일치" }
        }
      }
    },
    "/api/oauth/threads/connect": {
      "get": {
        "tags": ["OAuth"],
        "summary": "Threads 채널 연결 시작 (테넌트 관리자 전용, 302 리다이렉트)",
        "description": "Threads OAuth 동의 화면으로 리다이렉트합니다. 브라우저 세션이 필요합니다.",
        "responses": {
          "302": { "description": "Threads 인증 페이지로 리다이렉트" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "500": { "description": "NOT_CONFIGURED — Threads 연동 환경변수 미설정" }
        }
      }
    },
    "/api/oauth/threads/callback": {
      "get": {
        "tags": ["OAuth"],
        "summary": "Threads OAuth 콜백 (302 리다이렉트)",
        "description": "Threads가 동의 완료 후 리다이렉트하는 엔드포인트입니다. 처리 결과와 무관하게 /team으로 리다이렉트되며 ?threads=connected|error 쿼리로 결과를 전달합니다.",
        "parameters": [
          { "name": "code", "in": "query", "schema": { "type": "string" } },
          { "name": "state", "in": "query", "schema": { "type": "string" } },
          { "name": "error", "in": "query", "schema": { "type": "string" } }
        ],
        "responses": { "302": { "description": "/team?threads=connected 또는 /team?threads=error로 리다이렉트" } }
      }
    },
    "/api/public/approve/{token}": {
      "parameters": [{ "name": "token", "in": "path", "required": true, "schema": { "type": "string" }, "description": "외부 승인 링크 발급 시 생성된 1회성 토큰" }],
      "get": {
        "tags": ["Public"],
        "summary": "외부 승인 링크로 콘텐츠 조회 (로그인 불필요)",
        "security": [],
        "responses": {
          "200": {
            "description": "성공",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "campaignName": { "type": "string" },
                    "bodyText": { "type": "string" },
                    "imageUrl": { "type": ["string", "null"] },
                    "channelCode": { "type": "string" }
                  }
                }
              }
            }
          },
          "404": { "description": "NOT_FOUND — 유효하지 않거나 이미 처리된 링크" }
        }
      },
      "post": {
        "tags": ["Public"],
        "summary": "외부 승인 링크로 콘텐츠 승인/반려 (로그인 불필요)",
        "description": "토큰은 컨펌 대기(pending_approval) 상태에서만 유효하며, 처리 즉시 소진되어 재사용할 수 없습니다.",
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["action"],
                "properties": {
                  "action": { "type": "string", "enum": ["approve", "reject"] },
                  "approverLabel": { "type": "string", "maxLength": 100 },
                  "reason": { "type": "string", "minLength": 1, "maxLength": 1000, "description": "action이 reject일 때 필수" }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "성공", "content": { "application/json": { "schema": { "type": "object", "properties": { "success": { "type": "boolean" } } } } } },
          "400": { "$ref": "#/components/responses/ValidationError" },
          "404": { "description": "NOT_FOUND — 유효하지 않거나 이미 처리된 링크" }
        }
      }
    },
    "/api/reports/export": {
      "get": {
        "tags": ["Reports"],
        "summary": "성과 데이터 CSV 내보내기 (Pro 티어 전용)",
        "parameters": [{ "name": "period", "in": "query", "schema": { "type": "string", "default": "30" }, "description": "최근 N일, 또는 \"all\"" }],
        "responses": {
          "200": { "description": "CSV 파일", "content": { "text/csv": { "schema": { "type": "string" } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "402": { "description": "TIER_REQUIRED — Pro 티어 전용" }
        }
      }
    },
    "/api/subscription": {
      "get": {
        "tags": ["Subscription"],
        "summary": "현재 구독 티어와 사용량 조회",
        "responses": {
          "200": {
            "description": "성공",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "subscription": { "type": "object", "description": "Subscription 레코드(티어, 한도)" },
                    "usage": {
                      "type": "object",
                      "properties": {
                        "seats": { "$ref": "#/components/schemas/UsageCounter" },
                        "campaignsThisMonth": { "$ref": "#/components/schemas/UsageCounter" },
                        "aiDraftsThisMonth": { "$ref": "#/components/schemas/UsageCounter" },
                        "approvers": { "$ref": "#/components/schemas/UsageCounter" }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "description": "NO_ACTIVE_SUBSCRIPTION" }
        }
      }
    },
    "/api/team/invite": {
      "post": {
        "tags": ["Team"],
        "summary": "팀원 초대 (테넌트 관리자 전용)",
        "description": "구독 시트 한도 이내에서만 초대할 수 있으며, 초대 이메일이 발송됩니다.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["email", "name", "roles"],
                "properties": {
                  "email": { "type": "string", "format": "email" },
                  "name": { "type": "string", "minLength": 1, "maxLength": 100 },
                  "roles": { "type": "array", "items": { "type": "string", "enum": ["tenant_admin", "approver", "member"] }, "minItems": 1 }
                }
              }
            }
          }
        },
        "responses": {
          "201": { "description": "생성됨", "content": { "application/json": { "schema": { "type": "object", "properties": { "user": { "type": "object" } } } } } },
          "400": { "$ref": "#/components/responses/ValidationError" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "402": { "description": "TIER_LIMIT_EXCEEDED — 팀원 시트 한도 초과" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "409": { "description": "EMAIL_ALREADY_EXISTS" }
        }
      }
    },
    "/api/team/{userId}/roles": {
      "patch": {
        "tags": ["Team"],
        "summary": "팀원 역할 변경 (테넌트 관리자 전용)",
        "description": "테넌트 내 마지막 tenant_admin/approver 해제는 차단되며, 승인권자 신규 지정 시 티어 한도를 확인합니다.",
        "parameters": [{ "name": "userId", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } }],
        "requestBody": {
          "required": true,
          "content": { "application/json": { "schema": { "type": "object", "required": ["roles"], "properties": { "roles": { "type": "array", "items": { "type": "string", "enum": ["tenant_admin", "approver", "member"] }, "minItems": 1 } } } } }
        },
        "responses": {
          "200": { "description": "성공", "content": { "application/json": { "schema": { "type": "object", "properties": { "roles": { "type": "array", "items": { "type": "object" } } } } } } },
          "400": { "$ref": "#/components/responses/ValidationError" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "402": { "description": "TIER_LIMIT_EXCEEDED — 승인권자 한도 초과" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "description": "LAST_ROLE_HOLDER — 마지막 관리자/승인권자 해제 불가" }
        }
      }
    },
    "/api/team/{userId}/status": {
      "post": {
        "tags": ["Team"],
        "summary": "팀원 활성화/비활성화 (테넌트 관리자 전용)",
        "description": "참조 무결성 보호를 위해 하드 삭제 대신 status를 disabled로 전환합니다. 본인 계정 및 마지막 관리자/승인권자는 비활성화할 수 없습니다.",
        "parameters": [{ "name": "userId", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } }],
        "requestBody": {
          "required": true,
          "content": { "application/json": { "schema": { "type": "object", "required": ["status"], "properties": { "status": { "type": "string", "enum": ["active", "disabled"] } } } } }
        },
        "responses": {
          "200": { "description": "성공", "content": { "application/json": { "schema": { "type": "object", "properties": { "user": { "type": "object" } } } } } },
          "400": { "description": "VALIDATION_ERROR 또는 CANNOT_DISABLE_SELF" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "description": "LAST_ROLE_HOLDER" }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "sessionCookie": {
        "type": "apiKey",
        "in": "cookie",
        "name": "authjs.session-token",
        "description": "Auth.js(next-auth v5) JWT 세션 쿠키. 프로덕션(HTTPS)에서는 `__Secure-authjs.session-token`으로 내려갑니다. /login 화면의 폼 로그인으로 발급됩니다 — 외부에서 프로그램적으로 발급받는 API 키는 아닙니다."
      },
      "cronSecret": {
        "type": "http",
        "scheme": "bearer",
        "description": "Vercel Cron 전용. Authorization: Bearer <CRON_SECRET> 헤더로 인증합니다."
      }
    },
    "responses": {
      "Unauthorized": { "description": "UNAUTHENTICATED — 로그인 필요", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
      "Forbidden": { "description": "FORBIDDEN — 역할 권한 부족", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
      "NotFound": { "description": "NOT_FOUND", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
      "ValidationError": { "description": "VALIDATION_ERROR — 요청 필드가 스키마를 위반함", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
    },
    "schemas": {
      "Error": {
        "type": "object",
        "required": ["error"],
        "properties": {
          "error": { "type": "string", "description": "예: VALIDATION_ERROR, UNAUTHENTICATED, NOT_FOUND, INVALID_STATE, TIER_LIMIT_EXCEEDED" },
          "message": { "type": "string" },
          "details": { "type": "object", "description": "Zod 검증 실패 시 필드별 오류(safeParse().error.flatten())" }
        }
      },
      "Campaign": {
        "type": "object",
        "description": "테넌트별 캠페인 레코드. 상세 조회(GET /api/campaigns/{id})에는 contents, channels가 함께 포함됩니다.",
        "properties": {
          "id": { "type": "string", "format": "uuid" },
          "tenantId": { "type": "string", "format": "uuid" },
          "name": { "type": "string" },
          "goal": { "type": ["string", "null"] },
          "status": { "type": "string", "enum": ["planning", "in_progress", "completed", "archived"] },
          "startDate": { "type": ["string", "null"], "format": "date-time" },
          "endDate": { "type": ["string", "null"], "format": "date-time" },
          "defaultApproverId": { "type": "string", "format": "uuid" },
          "createdAt": { "type": "string", "format": "date-time" }
        },
        "additionalProperties": true
      },
      "Content": {
        "type": "object",
        "description": "캠페인에 속한 채널별 콘텐츠(포스트) 레코드. 상세 조회에는 versions, approvalHistory가 함께 포함됩니다.",
        "properties": {
          "id": { "type": "string", "format": "uuid" },
          "campaignId": { "type": "string", "format": "uuid" },
          "channelCode": { "type": "string" },
          "bodyText": { "type": "string" },
          "imageUrl": { "type": ["string", "null"] },
          "status": { "type": "string", "enum": ["draft", "pending_approval", "ready_to_publish", "published"] },
          "aiGenerated": { "type": "boolean" },
          "scheduledPublishAt": { "type": ["string", "null"], "format": "date-time" },
          "createdAt": { "type": "string", "format": "date-time" }
        },
        "additionalProperties": true
      },
      "Attachment": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "format": "uuid" },
          "campaignId": { "type": "string", "format": "uuid" },
          "url": { "type": "string", "format": "uri" },
          "filename": { "type": "string" },
          "contentType": { "type": "string" },
          "sizeBytes": { "type": "integer" }
        },
        "additionalProperties": true
      },
      "PerformanceMetric": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "format": "uuid" },
          "contentId": { "type": "string", "format": "uuid" },
          "views": { "type": "integer" },
          "likes": { "type": "integer" },
          "comments": { "type": "integer" },
          "shares": { "type": "integer" },
          "recordedAt": { "type": "string", "format": "date-time" }
        },
        "additionalProperties": true
      },
      "UsageCounter": {
        "type": "object",
        "properties": {
          "used": { "type": "integer" },
          "limit": { "type": ["integer", "null"], "description": "null이면 무제한" }
        }
      }
    }
  }
}
