import { describe, expect, it, beforeEach, vi } from "vitest"

import { api } from "@/convex/_generated/api"

const mutationMock = vi.fn()

vi.mock("@/server/convex-client", () => ({
  createConvexClient: () => ({
    mutation: mutationMock,
    query: vi.fn(),
  }),
  ConvexConfigurationError: class extends Error {},
}))

describe("POST /api/machines/chat/messages", () => {
  beforeEach(() => {
    mutationMock.mockReset()
  })

  it("aceita mensagem somente com anexo (body vazio) e encaminha ao Convex", async () => {
    mutationMock.mockResolvedValue({ ok: true })

    const payload = {
      action: "send",
      machineToken: "token-attach-only",
      ticketId: "ticket_1",
      attachments: [{ storageId: "storage_1", name: "arquivo.pdf", size: 123, type: "application/pdf" }],
    }

    const { POST } = await import("./route")
    const response = await POST(
      new Request("http://localhost/api/machines/chat/messages", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      })
    )

    expect(response.status).toBe(200)
    expect(await response.json()).toEqual({ ok: true })
    expect(mutationMock).toHaveBeenCalledWith(api.liveChat.postMachineMessage, {
      machineToken: payload.machineToken,
      ticketId: payload.ticketId,
      body: "",
      attachments: payload.attachments,
    })
  })

  it("rejeita mensagem vazia (sem body e sem anexos)", async () => {
    const payload = { action: "send", machineToken: "token-empty", ticketId: "ticket_1" }

    const { POST } = await import("./route")
    const response = await POST(
      new Request("http://localhost/api/machines/chat/messages", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      })
    )

    expect(response.status).toBe(400)
    const body = await response.json()
    expect(body).toHaveProperty("error", "Payload invalido")
    expect(mutationMock).not.toHaveBeenCalled()
  })

  it("rejeita body somente com espaços quando não há anexos", async () => {
    const payload = { action: "send", machineToken: "token-spaces", ticketId: "ticket_1", body: "   " }

    const { POST } = await import("./route")
    const response = await POST(
      new Request("http://localhost/api/machines/chat/messages", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      })
    )

    expect(response.status).toBe(400)
    const body = await response.json()
    expect(body).toHaveProperty("error", "Payload invalido")
    expect(mutationMock).not.toHaveBeenCalled()
  })
})

