openapi: 3.1.0
info:
  title: ZaChat API
  version: "1.1.0"
  summary: Tích hợp chat Zalo (cá nhân & Zalo OA) và Kênh chung nội bộ của doanh nghiệp vào CRM / phần mềm nội bộ.
  description: |
    CRM của bạn đọc và gửi tin qua cả nick Zalo cá nhân (`zalo_personal`) lẫn Zalo Official Account (`zalo_oa`)
    đã kết nối trên ZaChat trong cùng một chuẩn API, đồng bộ 2 chiều Kênh chung của tổ chức, và nhận sự kiện mới
    về CRM theo thời gian thực qua webhook.

    - Kết nối nick Zalo (quét QR với nick cá nhân, cấp quyền OAuth với Zalo OA) làm trên ZaChat (web / máy tính); API không quét QR hay nối OA mới.
    - Trường `snake_case`, thời gian là Unix **mili giây**. Thiếu `channel` được hiểu là `zalo_personal`; ẩn / hiện tính năng dựa vào `capabilities` của từng nick (bỏ qua tên lạ).
    - Hội thoại người quét nick để chế độ riêng tư không truy cập được qua API và không có trong webhook.
    - Hướng dẫn đầy đủ (Zalo OA, hạn trả lời 7 ngày, người thao tác `user_id`, gửi tin, Kênh chung, webhook, kiểm chữ ký): https://zachat.vn/docs/tich-hop-crm

    API key và webhook: chủ tổ chức (gói Doanh nghiệp trở lên) tự tạo trong ZaChat → Cài đặt → API & Webhook.
    Chưa có gói / đang dùng thử: https://zachat.vn/tich-hop-zalo-crm — doanh nghiệp không có lập trình viên được
    ZaChat hỗ trợ tích hợp miễn phí.
  contact:
    name: ZaChat
    url: https://zachat.vn/tich-hop-zalo-crm
servers:
  - url: https://api.zachat.vn/api/v1
security:
  - apiKey: []
tags:
  - name: Nick & nhân viên
  - name: Hội thoại & tin nhắn
  - name: Gửi tin
  - name: Thao tác trên tin
  - name: Kết bạn
  - name: Kênh chung
    description: Chat nội bộ của tổ chức. Đọc dùng quyền `messages:read`; tải tệp / gửi / sửa / thu hồi dùng `messages:send`. Webhook để trống sự kiện ("mọi sự kiện") cũng nhận `team_channel.*` (`account_id = null`).

paths:
  /accounts:
    get:
      tags: [Nick & nhân viên]
      summary: Danh sách nick Zalo trong phạm vi API key
      operationId: listAccounts
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { $ref: "#/components/schemas/Account" } }
        default: { $ref: "#/components/responses/Error" }

  /team:
    get:
      tags: [Nick & nhân viên]
      summary: Thành viên tổ chức (lấy user_id cho lệnh ghi)
      description: Cần quyền `team:read`. `assigned_account_ids` chỉ để tham khảo, API không dùng để chặn.
      operationId: listTeam
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { $ref: "#/components/schemas/TeamMember" } }
        default: { $ref: "#/components/responses/Error" }

  /accounts/{account_id}/threads:
    get:
      tags: [Hội thoại & tin nhắn]
      summary: Đồng bộ danh sách hội thoại (cũ → mới theo thời điểm cập nhật)
      description: |
        Gọi tiếp với `cursor = next_cursor` tới khi `next_cursor` là null (trang có thể ít hơn `limit`, kể cả rỗng).
        Lưu `sync_cursor` của trang cuối; lần sau gọi với `cursor = sync_cursor` để chỉ lấy hội thoại có thay đổi.
      operationId: listThreads
      parameters:
        - $ref: "#/components/parameters/AccountId"
        - { name: cursor, in: query, schema: { type: string } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 50 } }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { $ref: "#/components/schemas/Thread" } }
                  next_cursor: { type: [string, "null"] }
                  sync_cursor: { type: [string, "null"] }
        default: { $ref: "#/components/responses/Error" }

  /accounts/{account_id}/threads/{thread_id}/reply-window:
    get:
      tags: [Hội thoại & tin nhắn]
      summary: Kiểm tra hạn trả lời 7 ngày của hội thoại Zalo OA
      description: |
        Chỉ áp dụng cho nick có `"reply_window"` trong `capabilities` (`channel = "zalo_oa"`).
        Gọi với nick cá nhân trả `422 NOT_SUPPORTED`; OA đang offline / mất quyền trả `409 ACCOUNT_OFFLINE`.
        Nếu chưa xác định được mốc tương tác, cả 4 trường đều là `null`.
      operationId: getReplyWindow
      parameters:
        - $ref: "#/components/parameters/AccountId"
        - $ref: "#/components/parameters/ThreadId"
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReplyWindow" }
        default: { $ref: "#/components/responses/Error" }

  /accounts/{account_id}/threads/{thread_id}/messages:
    get:
      tags: [Hội thoại & tin nhắn]
      summary: Lịch sử tin của hội thoại (trang mới nhất, xếp cũ → mới)
      description: Lịch sử có từ lúc nick kết nối ZaChat — Zalo không cho tải tin 1-1 cũ hơn.
      operationId: listMessages
      parameters:
        - $ref: "#/components/parameters/AccountId"
        - $ref: "#/components/parameters/ThreadId"
        - { name: before, in: query, description: "`next_before` của trang trước", schema: { type: string } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 50 } }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { $ref: "#/components/schemas/Message" } }
                  next_before: { type: [string, "null"] }
        default: { $ref: "#/components/responses/Error" }
    post:
      tags: [Gửi tin]
      summary: Gửi tin (chữ, ảnh, video, ghi âm, tệp, sticker, vị trí)
      description: |
        Bắt buộc `idempotency_key`: gửi lại cùng key → không gửi lần 2, trả kết quả cũ (200).
        Zalo phản hồi chậm (> 25 giây) → 202 `pending`, kết quả cuối qua webhook `message.sent` / `message.failed`.
      operationId: sendMessage
      parameters:
        - $ref: "#/components/parameters/AccountId"
        - $ref: "#/components/parameters/ThreadId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SendMessageRequest" }
            examples:
              text: { value: { idempotency_key: "crm-msg-8812", type: text, text: "Dạ shop chào anh ạ", user_id: "b21e…" } }
              reply: { value: { idempotency_key: "crm-msg-8813", type: text, text: "Dạ còn ạ", quote_msg_id: "7234567890000" } }
              photo: { value: { idempotency_key: "crm-msg-8814", type: photo, media_id: "med_3f9a…", text: "Mẫu mới về" } }
              sticker: { value: { idempotency_key: "crm-msg-8815", type: sticker, sticker: { id: 21455, category_id: 10302, type: 7 } } }
      responses:
        "201": { $ref: "#/components/responses/Sent" }
        "200": { $ref: "#/components/responses/Sent" }
        "202": { $ref: "#/components/responses/Pending" }
        default: { $ref: "#/components/responses/Error" }

  /accounts/{account_id}/threads/{thread_id}/albums:
    post:
      tags: [Gửi tin]
      summary: Gửi nhiều ảnh (2–20 ảnh thành album trên Zalo cá nhân; 2–10 ảnh gửi lần lượt trên Zalo OA)
      description: |
        Nếu gửi lỗi giữa chừng (sau khi đã gửi được ít nhất 1 ảnh), `failed_media_ids` chứa các `media_id` chưa gửi được —
        CRM kiểm tra `messages.length` và gửi lại các id đó bằng `idempotency_key` mới.
      operationId: sendAlbum
      parameters:
        - $ref: "#/components/parameters/AccountId"
        - $ref: "#/components/parameters/ThreadId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [idempotency_key, media_ids]
              properties:
                idempotency_key: { $ref: "#/components/schemas/IdempotencyKey" }
                media_ids: { type: array, minItems: 2, maxItems: 20, items: { type: string }, description: "Tối đa 20 ảnh với zalo_personal, 10 ảnh với zalo_oa" }
                user_id: { $ref: "#/components/schemas/ActorUserId" }
      responses:
        "201": { $ref: "#/components/responses/AlbumSent" }
        "200": { $ref: "#/components/responses/AlbumSent" }
        "202": { $ref: "#/components/responses/Pending" }
        default: { $ref: "#/components/responses/Error" }

  /accounts/{account_id}/threads/{thread_id}/read:
    post:
      tags: [Thao tác trên tin]
      summary: Đánh dấu hội thoại đã đọc (đồng bộ với app ZaChat)
      operationId: markRead
      parameters:
        - $ref: "#/components/parameters/AccountId"
        - $ref: "#/components/parameters/ThreadId"
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, properties: { status: { const: read } } } } } }
        default: { $ref: "#/components/responses/Error" }

  /media:
    post:
      tags: [Gửi tin]
      summary: Tải tệp lên (tối đa 50MB) để gửi — media_id dùng được 24 giờ
      operationId: uploadMedia
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file]
              properties:
                file: { type: string, format: binary }
      responses:
        "201":
          description: Đã tải lên
          content:
            application/json:
              schema: { $ref: "#/components/schemas/UploadedMedia" }
        default: { $ref: "#/components/responses/Error" }

  /accounts/{account_id}/messages/{msg_id}:
    get:
      tags: [Hội thoại & tin nhắn]
      summary: Một tin nhắn
      operationId: getMessage
      parameters:
        - $ref: "#/components/parameters/AccountId"
        - $ref: "#/components/parameters/MsgId"
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { type: object, properties: { data: { $ref: "#/components/schemas/Message" } } }
        default: { $ref: "#/components/responses/Error" }

  /accounts/{account_id}/messages/{msg_id}/forward:
    post:
      tags: [Gửi tin]
      summary: Chuyển tiếp tin tới 1–20 hội thoại (mỗi người nhận tính một tin vào hạn mức)
      operationId: forwardMessage
      parameters:
        - $ref: "#/components/parameters/AccountId"
        - $ref: "#/components/parameters/MsgId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [thread_ids]
              properties:
                thread_ids: { type: array, minItems: 1, maxItems: 20, items: { type: string } }
                user_id: { $ref: "#/components/schemas/ActorUserId" }
      responses:
        "200":
          description: Kết quả từng hội thoại
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        thread_id: { type: string }
                        status: { enum: [sent, failed] }
                        message_id: { type: [string, "null"] }
                        error: { type: [string, "null"] }
        default: { $ref: "#/components/responses/Error" }

  /accounts/{account_id}/messages/{msg_id}/recall:
    post:
      tags: [Thao tác trên tin]
      summary: Thu hồi tin do nick gửi
      operationId: recallMessage
      parameters:
        - $ref: "#/components/parameters/AccountId"
        - $ref: "#/components/parameters/MsgId"
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, properties: { status: { const: recalled } } } } } }
        default: { $ref: "#/components/responses/Error" }

  /accounts/{account_id}/messages/{msg_id}/reactions:
    get:
      tags: [Thao tác trên tin]
      summary: Ai đã thả cảm xúc gì
      operationId: listReactions
      parameters:
        - $ref: "#/components/parameters/AccountId"
        - $ref: "#/components/parameters/MsgId"
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        sender_zalo_id: { type: string }
                        icon: { type: string }
                        name: { type: [string, "null"] }
                        avatar: { type: [string, "null"] }
                        is_self: { type: boolean }
        default: { $ref: "#/components/responses/Error" }
    post:
      tags: [Thao tác trên tin]
      summary: Thả cảm xúc
      operationId: addReaction
      parameters:
        - $ref: "#/components/parameters/AccountId"
        - $ref: "#/components/parameters/MsgId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [icon]
              properties:
                icon:
                  type: string
                  description: "👍 ❤️ 😂 😮 😭 😡 (nhận cả mã Zalo /-strong, /-heart, :>, :o, :-((, :-h)"
                  examples: ["❤️"]
      responses:
        "200": { $ref: "#/components/responses/Reactions" }
        default: { $ref: "#/components/responses/Error" }
    delete:
      tags: [Thao tác trên tin]
      summary: Gỡ mọi cảm xúc của nick trên tin
      operationId: removeReaction
      parameters:
        - $ref: "#/components/parameters/AccountId"
        - $ref: "#/components/parameters/MsgId"
      responses:
        "200": { $ref: "#/components/responses/Reactions" }
        default: { $ref: "#/components/responses/Error" }

  /accounts/{account_id}/messages/{msg_id}/pin:
    post:
      tags: [Thao tác trên tin]
      summary: Ghim tin (tối đa 3 / hội thoại)
      operationId: pinMessage
      parameters:
        - $ref: "#/components/parameters/AccountId"
        - $ref: "#/components/parameters/MsgId"
      responses:
        "200": { $ref: "#/components/responses/Pins" }
        default: { $ref: "#/components/responses/Error" }
    delete:
      tags: [Thao tác trên tin]
      summary: Bỏ ghim tin
      operationId: unpinMessage
      parameters:
        - $ref: "#/components/parameters/AccountId"
        - $ref: "#/components/parameters/MsgId"
      responses:
        "200": { $ref: "#/components/responses/Pins" }
        default: { $ref: "#/components/responses/Error" }

  /accounts/{account_id}/lookup-phone:
    post:
      tags: [Kết bạn]
      summary: Tìm người dùng Zalo theo số điện thoại (30 lượt / giờ / nick)
      operationId: lookupPhone
      parameters:
        - $ref: "#/components/parameters/AccountId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [phone], properties: { phone: { type: string, examples: ["0912345678"] } } }
      responses:
        "200":
          description: Tìm thấy — dùng thread_id để nhắn hoặc gửi lời mời kết bạn
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
                    properties:
                      thread_id: { type: string }
                      name: { type: string }
                      avatar: { type: [string, "null"] }
                      is_friend: { type: boolean }
        default: { $ref: "#/components/responses/Error" }

  /accounts/{account_id}/friend-requests:
    get:
      tags: [Kết bạn]
      summary: Lời mời kết bạn đang chờ (đã nhận / đã gửi)
      operationId: listFriendRequests
      parameters:
        - $ref: "#/components/parameters/AccountId"
        - { name: direction, in: query, schema: { enum: [received, sent], default: received } }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { $ref: "#/components/schemas/FriendRequest" } }
        default: { $ref: "#/components/responses/Error" }
    post:
      tags: [Kết bạn]
      summary: Gửi lời mời kết bạn (tính chung hạn mức kết bạn mỗi ngày của tổ chức)
      operationId: sendFriendRequest
      parameters:
        - $ref: "#/components/parameters/AccountId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [zalo_id]
              properties:
                zalo_id: { type: string }
                message: { type: string, maxLength: 150 }
                user_id: { $ref: "#/components/schemas/ActorUserId" }
      responses:
        "201":
          description: Đã gửi
          content:
            application/json:
              schema:
                type: object
                properties:
                  status: { const: sent }
                  zalo_id: { type: string }
                  daily_used: { type: integer }
                  daily_limit: { type: integer }
        default: { $ref: "#/components/responses/Error" }

  /accounts/{account_id}/friend-requests/{zalo_id}/accept:
    post:
      tags: [Kết bạn]
      summary: Đồng ý lời mời kết bạn
      operationId: acceptFriendRequest
      parameters:
        - $ref: "#/components/parameters/AccountId"
        - $ref: "#/components/parameters/ZaloId"
      responses:
        "200": { $ref: "#/components/responses/FriendAction" }
        default: { $ref: "#/components/responses/Error" }

  /accounts/{account_id}/friend-requests/{zalo_id}/reject:
    post:
      tags: [Kết bạn]
      summary: Từ chối lời mời kết bạn
      operationId: rejectFriendRequest
      parameters:
        - $ref: "#/components/parameters/AccountId"
        - $ref: "#/components/parameters/ZaloId"
      responses:
        "200": { $ref: "#/components/responses/FriendAction" }
        default: { $ref: "#/components/responses/Error" }

  /accounts/{account_id}/friend-requests/{zalo_id}:
    delete:
      tags: [Kết bạn]
      summary: Thu hồi lời mời đã gửi
      operationId: cancelFriendRequest
      parameters:
        - $ref: "#/components/parameters/AccountId"
        - $ref: "#/components/parameters/ZaloId"
      responses:
        "200": { $ref: "#/components/responses/FriendAction" }
        default: { $ref: "#/components/responses/Error" }

  /team-channel/messages:
    get:
      tags: [Kênh chung]
      summary: Lịch sử tin của Kênh chung (trang mới nhất, xếp cũ → mới)
      description: Tải thêm tin cũ hơn ("load more") bằng cách truyền `before = next_before` của trang trước (`null` = đã hết).
      operationId: listTeamChannelMessages
      parameters:
        - { name: before, in: query, description: "`next_before` của trang trước", schema: { type: string } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 50 } }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { $ref: "#/components/schemas/TeamChannelMessage" } }
                  next_before: { type: [string, "null"] }
        default: { $ref: "#/components/responses/Error" }
    post:
      tags: [Kênh chung]
      summary: Gửi tin vào Kênh chung (chữ, tệp đính kèm, @nhắc thành viên, trả lời)
      description: |
        Bắt buộc `idempotency_key`: gửi lại cùng key → không gửi lần 2, trả kết quả cũ (200).
        Kênh chung lưu trực tiếp trên ZaChat nên luôn phản hồi ngay (201 / 200), không có 202 `pending`.
      operationId: sendTeamChannelMessage
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SendTeamChannelMessageRequest" }
            examples:
              text:
                summary: Gửi chữ
                value: { idempotency_key: "crm-team-101", text: "Đơn DH102 cần kiểm kho gấp", user_id: "b21e0000-0000-4000-8000-000000000001" }
              mention_and_reply:
                summary: Trả lời & @nhắc thành viên
                value:
                  idempotency_key: "crm-team-102"
                  text: "@Nguyễn An kho báo còn đủ hàng nhé"
                  mention_user_ids: ["8f0c0000-0000-4000-8000-000000000001"]
                  quote_msg_id: "330e8400-e29b-41d4-a716-446655440000"
                  user_id: "b21e0000-0000-4000-8000-000000000001"
              attachments:
                summary: Gửi ảnh / tệp đính kèm
                value:
                  idempotency_key: "crm-team-103"
                  text: "Phiếu xuất kho"
                  attachment_ids: ["550e8400-e29b-41d4-a716-446655440000"]
      responses:
        "201": { $ref: "#/components/responses/TeamChannelSent" }
        "200": { $ref: "#/components/responses/TeamChannelSent" }
        default: { $ref: "#/components/responses/Error" }

  /team-channel/attachments:
    post:
      tags: [Kênh chung]
      summary: Tải ảnh / video / tệp lên (tối đa 20MB) để đính kèm vào Kênh chung
      description: 30 tệp / phút mỗi tổ chức; tối đa 50 tệp đã tải lên mà chưa gửi (quá thì 429 `RATE_LIMITED`). Tệp không gửi tự xoá sau 24 giờ.
      operationId: uploadTeamChannelAttachment
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file]
              properties:
                file: { type: string, format: binary }
                file_name: { type: string, description: Tên tệp gốc UTF-8 (tuỳ chọn) }
      responses:
        "201":
          description: Đã tải lên
          content:
            application/json:
              schema: { $ref: "#/components/schemas/UploadedTeamAttachment" }
        default: { $ref: "#/components/responses/Error" }

  /team-channel/messages/{msg_id}:
    get:
      tags: [Kênh chung]
      summary: Một tin nhắn Kênh chung
      operationId: getTeamChannelMessage
      parameters:
        - $ref: "#/components/parameters/MsgId"
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { type: object, properties: { data: { $ref: "#/components/schemas/TeamChannelMessage" } } }
        default: { $ref: "#/components/responses/Error" }
    patch:
      tags: [Kênh chung]
      summary: Sửa tin Kênh chung (chỉ người đã gửi tin mới sửa được)
      operationId: editTeamChannelMessage
      parameters:
        - $ref: "#/components/parameters/MsgId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/EditTeamChannelMessageRequest" }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  status: { const: edited }
                  message: { $ref: "#/components/schemas/TeamChannelMessage" }
        default: { $ref: "#/components/responses/Error" }

  /team-channel/messages/{msg_id}/recall:
    post:
      tags: [Kênh chung]
      summary: Thu hồi tin Kênh chung (chỉ người đã gửi tin mới thu hồi được)
      operationId: recallTeamChannelMessage
      parameters:
        - $ref: "#/components/parameters/MsgId"
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                user_id: { $ref: "#/components/schemas/ActorUserId" }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { type: object, properties: { status: { const: recalled } } }
        default: { $ref: "#/components/responses/Error" }

webhooks:
  message.received:
    post:
      summary: Tin đến
      description: Ký HMAC — xem components.schemas.WebhookEnvelope. Trả 2xx trong 10 giây.
      requestBody: { $ref: "#/components/requestBodies/MessageEvent" }
      responses: { "200": { description: Đã nhận } }
  message.sent:
    post:
      summary: Tin đi (từ API, app ZaChat hoặc điện thoại)
      requestBody: { $ref: "#/components/requestBodies/MessageEvent" }
      responses: { "200": { description: Đã nhận } }
  message.failed:
    post:
      summary: Lệnh gửi qua API đã trả 202 rồi thất bại
      requestBody:
        content:
          application/json:
            schema:
              allOf:
                - $ref: "#/components/schemas/WebhookEnvelope"
                - properties:
                    data:
                      type: object
                      properties:
                        account_id: { type: string }
                        thread_id: { type: string }
                        idempotency_key: { type: string }
                        error: { type: string }
      responses: { "200": { description: Đã nhận } }
  message.recalled:
    post:
      summary: Tin bị thu hồi
      requestBody:
        content:
          application/json:
            schema:
              allOf:
                - $ref: "#/components/schemas/WebhookEnvelope"
                - properties:
                    data: { type: object, properties: { account_id: { type: string }, thread_id: { type: string }, msg_id: { type: string } } }
      responses: { "200": { description: Đã nhận } }
  message.reaction:
    post:
      summary: Có người thả / gỡ cảm xúc
      requestBody:
        content:
          application/json:
            schema:
              allOf:
                - $ref: "#/components/schemas/WebhookEnvelope"
                - properties:
                    data:
                      type: object
                      properties:
                        account_id: { type: string }
                        thread_id: { type: string }
                        msg_id: { type: string }
                        sender_zalo_id: { type: [string, "null"] }
                        icon: { type: [string, "null"] }
                        action: { enum: [add, remove] }
                        reactions: { type: object, additionalProperties: { type: integer } }
      responses: { "200": { description: Đã nhận } }
  message.pinned:
    post:
      summary: Danh sách tin ghim của hội thoại thay đổi
      requestBody:
        content:
          application/json:
            schema:
              allOf:
                - $ref: "#/components/schemas/WebhookEnvelope"
                - properties:
                    data:
                      type: object
                      properties:
                        account_id: { type: string }
                        thread_id: { type: string }
                        pinned_messages: { type: array, items: { $ref: "#/components/schemas/PinnedMessage" } }
      responses: { "200": { description: Đã nhận } }
  account.status_changed:
    post:
      summary: Nick mất kết nối / kết nối lại
      requestBody:
        content:
          application/json:
            schema:
              allOf:
                - $ref: "#/components/schemas/WebhookEnvelope"
                - properties:
                    data: { type: object, properties: { account_id: { type: string }, is_online: { type: boolean }, reason: { type: [string, "null"] } } }
      responses: { "200": { description: Đã nhận } }
  friend.request_received:
    post:
      summary: Có người gửi lời mời kết bạn cho nick
      requestBody:
        content:
          application/json:
            schema:
              allOf:
                - $ref: "#/components/schemas/WebhookEnvelope"
                - properties:
                    data: { type: object, properties: { account_id: { type: string }, zalo_id: { type: string }, name: { type: [string, "null"] }, message: { type: [string, "null"] } } }
      responses: { "200": { description: Đã nhận } }
  friend.added:
    post:
      summary: Đã thành bạn bè
      requestBody:
        content:
          application/json:
            schema:
              allOf:
                - $ref: "#/components/schemas/WebhookEnvelope"
                - properties:
                    data: { type: object, properties: { account_id: { type: string }, zalo_id: { type: string }, name: { type: [string, "null"] } } }
      responses: { "200": { description: Đã nhận } }
  team_channel.message_created:
    post:
      summary: Tin mới trong Kênh chung (từ ứng dụng ZaChat hoặc qua API)
      requestBody: { $ref: "#/components/requestBodies/TeamChannelMessageEvent" }
      responses: { "200": { description: Đã nhận } }
  team_channel.message_edited:
    post:
      summary: Tin trong Kênh chung vừa được sửa
      requestBody: { $ref: "#/components/requestBodies/TeamChannelMessageEvent" }
      responses: { "200": { description: Đã nhận } }
  team_channel.message_recalled:
    post:
      summary: Tin trong Kênh chung bị thu hồi
      requestBody:
        content:
          application/json:
            schema:
              allOf:
                - $ref: "#/components/schemas/WebhookEnvelope"
                - properties:
                    data: { type: object, properties: { msg_id: { type: string }, user_id: { type: [string, "null"] } } }
      responses: { "200": { description: Đã nhận } }
  webhook.test:
    post:
      summary: Sự kiện thử khi cài đặt webhook
      requestBody:
        content:
          application/json:
            schema: { $ref: "#/components/schemas/WebhookEnvelope" }
      responses: { "200": { description: Đã nhận } }

components:
  securitySchemes:
    apiKey:
      type: http
      scheme: bearer
      bearerFormat: zk_live_…
      description: "Authorization: Bearer zk_live_… — giữ bí mật, chỉ dùng phía server."

  parameters:
    AccountId: { name: account_id, in: path, required: true, schema: { type: string, examples: ["acc_123456789"] } }
    ThreadId:
      name: thread_id
      in: path
      required: true
      description: Id người dùng (chat 1-1) hoặc nhóm; nên thêm tiền tố `g` khi gửi vào nhóm (vd. g7712…).
      schema: { type: string }
    MsgId: { name: msg_id, in: path, required: true, schema: { type: string } }
    ZaloId: { name: zalo_id, in: path, required: true, schema: { type: string } }

  requestBodies:
    MessageEvent:
      content:
        application/json:
          schema:
            allOf:
              - $ref: "#/components/schemas/WebhookEnvelope"
              - properties: { data: { $ref: "#/components/schemas/Message" } }
    TeamChannelMessageEvent:
      content:
        application/json:
          schema:
            allOf:
              - $ref: "#/components/schemas/WebhookEnvelope"
              - properties: { data: { $ref: "#/components/schemas/TeamChannelMessage" } }

  responses:
    Error:
      description: Lỗi
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    Sent:
      description: Đã gửi (201) / gửi lại cùng idempotency_key (200)
      content:
        application/json:
          schema:
            type: object
            properties:
              status: { const: sent }
              message: { $ref: "#/components/schemas/Message" }
              messages: { type: array, items: { $ref: "#/components/schemas/Message" } }
    AlbumSent:
      description: Đã gửi album (201) / gửi lại cùng idempotency_key (200)
      content:
        application/json:
          schema:
            type: object
            properties:
              status: { const: sent }
              message: { $ref: "#/components/schemas/Message" }
              messages: { type: array, items: { $ref: "#/components/schemas/Message" } }
              failed_media_ids:
                type: array
                items: { type: string }
                description: Các media_id chưa gửi được khi album bị lỗi giữa chừng (rỗng khi gửi đủ).
    TeamChannelSent:
      description: Đã gửi vào Kênh chung (201) / gửi lại cùng idempotency_key (200)
      content:
        application/json:
          schema:
            type: object
            properties:
              status: { const: sent }
              message: { $ref: "#/components/schemas/TeamChannelMessage" }
    Pending:
      description: Zalo phản hồi chậm — kết quả cuối qua webhook message.sent / message.failed
      content:
        application/json:
          schema: { type: object, properties: { status: { const: pending } } }
    Reactions:
      description: Tổng cảm xúc của tin
      content:
        application/json:
          schema: { type: object, properties: { reactions: { type: object, additionalProperties: { type: integer } } } }
    Pins:
      description: Tin đang ghim của hội thoại
      content:
        application/json:
          schema:
            type: object
            properties:
              pinned_messages: { type: array, items: { $ref: "#/components/schemas/PinnedMessage" } }
    FriendAction:
      description: OK
      content:
        application/json:
          schema:
            type: object
            properties:
              status: { enum: [accepted, rejected, cancelled] }
              zalo_id: { type: string }

  schemas:
    Channel:
      type: string
      enum: [zalo_personal, zalo_oa]
      description: Loại kênh của nick Zalo (thiếu trường này ở dữ liệu cũ thì hiểu là `zalo_personal`).

    ReplyWindow:
      type: object
      properties:
        last_interaction_at: { type: [integer, "null"], description: Unix ms lần tương tác cuối của khách với OA }
        expires_at: { type: [integer, "null"], description: Unix ms hết hạn trả lời 7 ngày }
        can_send: { type: [boolean, "null"], description: Còn trong hạn 7 ngày để gửi tin tư vấn không (null khi chưa xác định được mốc) }
        free_until: { type: [integer, "null"], description: Unix ms hết khung 48h miễn phí của Zalo OA (chỉ để tham khảo) }

    Error:
      type: object
      properties:
        error:
          type: object
          properties:
            code:
              enum:
                - VALIDATION_ERROR
                - UNAUTHORIZED
                - PLAN_EXPIRED
                - PLAN_NOT_INCLUDED
                - FORBIDDEN_SCOPE
                - ORG_SUSPENDED
                - ACCOUNT_NOT_FOUND
                - THREAD_NOT_VISIBLE
                - MESSAGE_NOT_FOUND
                - MEDIA_NOT_FOUND
                - MEDIA_NOT_ALLOWED
                - USER_NOT_FOUND
                - ACCOUNT_OFFLINE
                - INVALID_USER_ID
                - NOT_SUPPORTED
                - REPLY_WINDOW_EXPIRED
                - OA_PACKAGE_REQUIRED
                - RATE_LIMITED
                - QUOTA_EXCEEDED
                - ZALO_ERROR
                - SERVICE_RESTARTING
                - INTERNAL_ERROR
            message: { type: string }
            details: { type: object, additionalProperties: true, description: "Dữ liệu phụ (vd. `{ expires_at }` với `REPLY_WINDOW_EXPIRED`)" }

    IdempotencyKey:
      type: string
      pattern: "^[A-Za-z0-9._:-]{1,100}$"
      description: Duy nhất cho mỗi tin của bạn — gửi lại cùng key không gửi lần 2.

    ActorUserId:
      type: string
      description: Thành viên ZaChat đang thao tác (từ GET /team). Không truyền → chủ tổ chức.

    Account:
      type: object
      properties:
        id: { type: string, examples: ["acc_123456789"] }
        zalo_id: { type: string, description: uid Zalo cá nhân hoặc oa_id của Zalo OA }
        name: { type: string }
        avatar: { type: [string, "null"] }
        channel: { $ref: "#/components/schemas/Channel" }
        capabilities:
          type: array
          items: { type: string }
          description: |
            Danh sách thao tác loại nick này hỗ trợ (luôn trả đủ kể cả khi offline). CRM bỏ qua tên lạ.
            Giá trị hiện tại: `send_text`, `send_image`, `send_file`, `send_video`, `send_voice`, `sticker`, `location`,
            `album`, `quote`, `mentions`, `recall`, `reactions`, `pin`, `forward`, `lookup_phone`, `friend_requests`, `reply_window`.
        is_online: { type: boolean }

    TeamMember:
      type: object
      properties:
        user_id: { type: string }
        name: { type: string }
        email: { type: string }
        role: { enum: [OWNER, MANAGER, STAFF] }
        status: { type: string }
        assigned_account_ids: { type: array, items: { type: string } }

    Thread:
      type: object
      properties:
        id: { type: string }
        account_id: { type: string }
        channel: { $ref: "#/components/schemas/Channel" }
        name: { type: string }
        avatar: { type: [string, "null"] }
        is_group: { type: boolean }
        unread_count: { type: integer }
        last_message_preview: { type: [string, "null"] }
        last_message_at: { type: [integer, "null"] }
        last_message_is_outgoing: { type: boolean }
        is_pinned: { type: boolean }
        labels: { type: array, items: { type: string } }

    Media:
      type: object
      properties:
        url: { type: [string, "null"], description: Link Zalo có hạn — tải về nếu cần lưu lâu dài }
        thumbnail_url: { type: [string, "null"] }
        file_name: { type: [string, "null"] }
        file_size: { type: [integer, "null"] }
        mime_type: { type: [string, "null"] }
        width: { type: [integer, "null"] }
        height: { type: [integer, "null"] }
        duration_seconds: { type: [number, "null"] }

    Message:
      type: object
      properties:
        id: { type: string }
        account_id: { type: string }
        channel: { $ref: "#/components/schemas/Channel" }
        thread_id: { type: string }
        is_group: { type: boolean }
        direction: { enum: [in, out] }
        sender: { type: object, properties: { zalo_id: { type: string, description: "uid cá nhân hoặc user_id riêng theo OA (không gộp giữa OA và cá nhân)" }, name: { type: [string, "null"] } } }
        user_id: { type: [string, "null"], description: Nhân viên ZaChat đã gửi (tin out từ app / API) }
        source:
          type: [string, "null"]
          enum: [api, oa_manager, null]
          description: "\"api\" = gửi qua API mở; \"oa_manager\" = admin trả lời từ oa.zalo.me (tin realtime); null = gửi từ ứng dụng / lịch sử. Bot tự trả lời nên bỏ qua tin out / api / oa_manager để tránh vòng lặp."
        idempotency_key: { type: [string, "null"], description: idempotency_key của lệnh gửi qua API (khớp kết quả lệnh đã trả 202) }
        type: { enum: [text, photo, video, voice, file, sticker, link, location, contact_card, bank_card, call, system, recalled, other] }
        text: { type: [string, "null"], description: Chữ hoặc chú thích }
        media: { oneOf: [{ $ref: "#/components/schemas/Media" }, { type: "null" }] }
        sticker:
          oneOf:
            - type: object
              properties:
                id: { type: string }
                category_id: { type: [integer, "null"] }
                type: { type: [integer, "null"] }
                url: { type: [string, "null"] }
            - type: "null"
        location:
          oneOf:
            - type: object
              properties:
                latitude: { type: [number, "null"] }
                longitude: { type: [number, "null"] }
                address: { type: [string, "null"] }
                map_url: { type: [string, "null"] }
            - type: "null"
        quote:
          oneOf:
            - type: object
              properties:
                msg_id: { type: [string, "null"] }
                sender_id: { type: [string, "null"] }
                sender_name: { type: [string, "null"] }
                text: { type: [string, "null"] }
            - type: "null"
        mentions:
          type: array
          items: { type: object, properties: { user_id: { type: string }, offset: { type: integer }, length: { type: integer } } }
        reactions: { type: object, additionalProperties: { type: integer } }
        is_recalled: { type: boolean }
        is_pinned: { type: boolean }
        timestamp: { type: integer, description: Unix ms }
        raw_content: { type: string, description: Nội dung gốc từ Zalo }

    SendMessageRequest:
      type: object
      required: [idempotency_key]
      properties:
        idempotency_key: { $ref: "#/components/schemas/IdempotencyKey" }
        type: { enum: [text, photo, video, voice, file, sticker, location], default: text }
        text: { type: string, maxLength: 10000, description: "Nội dung (text) hoặc chú thích (photo / video). Tối đa 10.000 ký tự với zalo_personal, 2.000 ký tự với zalo_oa." }
        media_id: { type: string, description: Từ POST /media — với photo / video / voice / file }
        sticker:
          type: object
          properties:
            id: { type: integer }
            category_id: { type: integer }
            type: { type: integer, default: 7 }
        location:
          type: object
          properties:
            latitude: { type: number }
            longitude: { type: number }
            title: { type: string }
            address: { type: string }
        quote_msg_id: { type: string, description: Trả lời trích dẫn một tin trong cùng hội thoại }
        mentions:
          type: array
          description: Chỉ trong nhóm. user_id "-1" = @Tất cả; offset / length tính theo ký tự trong text.
          items:
            type: object
            required: [user_id, offset, length]
            properties:
              user_id: { type: string }
              offset: { type: integer }
              length: { type: integer }
        user_id: { $ref: "#/components/schemas/ActorUserId" }

    UploadedMedia:
      type: object
      properties:
        media_id: { type: string }
        url: { type: string }
        file_name: { type: string }
        mime_type: { type: string }
        file_size: { type: [integer, "null"] }
        width: { type: [integer, "null"] }
        height: { type: [integer, "null"] }
        expires_in_seconds: { type: integer }

    PinnedMessage:
      type: object
      properties:
        msg_id: { type: string }
        sender_name: { type: [string, "null"] }
        preview: { type: [string, "null"] }

    FriendRequest:
      type: object
      properties:
        zalo_id: { type: string }
        name: { type: string }
        avatar: { type: [string, "null"] }
        phone: { type: [string, "null"] }
        message: { type: [string, "null"] }
        requested_at: { type: [integer, "null"] }

    TeamChannelAttachment:
      type: object
      properties:
        id: { type: string, format: uuid }
        kind: { enum: [image, video, file] }
        file_name: { type: string }
        mime_type: { type: string }
        file_size: { type: integer }
        url: { type: string }
        thumbnail_url: { type: [string, "null"] }
        width: { type: [integer, "null"] }
        height: { type: [integer, "null"] }

    UploadedTeamAttachment:
      type: object
      properties:
        attachment_id: { type: string, format: uuid }
        kind: { enum: [image, video, file] }
        file_name: { type: string }
        mime_type: { type: string }
        file_size: { type: integer }
        url: { type: string }
        thumbnail_url: { type: [string, "null"] }
        width: { type: [integer, "null"] }
        height: { type: [integer, "null"] }

    TeamChannelMessage:
      type: object
      properties:
        id: { type: string, format: uuid }
        author:
          type: object
          properties:
            user_id: { type: [string, "null"], format: uuid }
            name: { type: string }
        source: { type: [string, "null"], enum: [api, null], description: "\"api\" = gửi qua API mở (webhook cũng báo lại tin bạn tự gửi — bot tự trả lời nên bỏ qua để tránh vòng lặp); null = gửi từ ứng dụng" }
        idempotency_key: { type: [string, "null"] }
        text: { type: [string, "null"] }
        attachments: { type: array, items: { $ref: "#/components/schemas/TeamChannelAttachment" } }
        mentions:
          type: array
          items:
            type: object
            properties:
              user_id: { type: string, format: uuid }
              name: { type: string }
        mention_all: { type: boolean }
        quote:
          oneOf:
            - type: object
              properties:
                msg_id: { type: string, format: uuid }
                sender_name: { type: string }
                text: { type: [string, "null"] }
                timestamp: { type: integer }
                is_recalled: { type: boolean }
            - type: "null"
        is_recalled: { type: boolean }
        edited_at: { type: [integer, "null"], description: Unix ms lần sửa gần nhất }
        timestamp: { type: integer, description: Unix ms thời điểm tạo }

    SendTeamChannelMessageRequest:
      type: object
      required: [idempotency_key]
      properties:
        idempotency_key: { $ref: "#/components/schemas/IdempotencyKey" }
        text: { type: string, maxLength: 4000, description: Nội dung chữ (được để trống nếu có attachment_ids) }
        attachment_ids:
          type: array
          maxItems: 10
          items: { type: string, format: uuid }
          description: Từ POST /team-channel/attachments
        mention_user_ids:
          type: array
          items: { type: string, format: uuid }
          description: Mảng user_id thành viên từ GET /team
        mention_all: { type: boolean, default: false }
        quote_msg_id: { type: string, format: uuid, description: Trả lời một tin trong Kênh chung }
        user_id: { $ref: "#/components/schemas/ActorUserId" }

    EditTeamChannelMessageRequest:
      type: object
      properties:
        text: { type: string, maxLength: 4000 }
        mention_user_ids: { type: array, items: { type: string, format: uuid } }
        mention_all: { type: boolean }
        user_id: { $ref: "#/components/schemas/ActorUserId" }

    WebhookEnvelope:
      type: object
      description: |
        Header: X-ZaChat-Event, X-ZaChat-Delivery (id chống trùng), X-ZaChat-Timestamp (giây),
        X-ZaChat-Signature = "sha256=" + hex(HMAC_SHA256(secret, timestamp + "." + raw_body)).
        Giao ít nhất một lần, không đảm bảo thứ tự — upsert theo id.
      properties:
        id: { type: string, description: Id lần gửi }
        event: { type: string }
        created_at: { type: integer }
        account_id: { type: [string, "null"] }
        channel:
          type: [string, "null"]
          enum: [zalo_personal, zalo_oa, null]
          description: Loại kênh của `account_id`; `null` khi `account_id = null` (`team_channel.*`, `webhook.test`).
        data: { type: object }
