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,
  }),
  ConvexConfigurationError: class extends Error {},
}))

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

  it("accepts the token mode payload", async () => {
    const payload = {
      machineToken: "token-123",
      hostname: "machine",
      metrics: { cpu: 50 },
    }
    mutationMock.mockResolvedValue({ ok: true, machineId: "machine-123" })

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

    expect(response.status).toBe(200)
    expect(mutationMock).toHaveBeenCalledWith(
      api.devices.heartbeat,
      expect.objectContaining({
        machineToken: "token-123",
        hostname: "machine",
        metrics: { cpu: 50 },
      })
    )
    const body = await response.json()
    expect(body).toEqual({ ok: true, machineId: "machine-123" })
  })

  it("accepts the provisioning mode payload", async () => {
    const payload = {
      provisioningCode: "a".repeat(32),
      hostname: "machine",
      os: { name: "Linux" },
      macAddresses: ["00:11:22:33"],
      serialNumbers: [],
    }
    mutationMock.mockResolvedValue({ ok: true, status: "updated", machineId: "machine-987" })

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

    expect(response.status).toBe(200)
    expect(mutationMock).toHaveBeenCalledWith(
      api.devices.upsertInventory,
      expect.objectContaining({
        provisioningCode: "a".repeat(32),
        hostname: "machine",
        os: { name: "Linux" },
        macAddresses: ["00:11:22:33"],
        serialNumbers: [],
        registeredBy: "agent:inventory",
      })
    )
    const body = await response.json()
    expect(body).toEqual({ ok: true, machineId: "machine-987", status: "updated" })
  })

  it("rejects unknown payloads", async () => {
    const { POST } = await import("./route")
    const response = await POST(
      new Request("http://localhost/api/machines/inventory", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ hostname: "machine" }),
      })
    )

    expect(response.status).toBe(400)
    const body = await response.json()
    expect(body).toEqual({ error: "Formato de payload não suportado" })
    expect(mutationMock).not.toHaveBeenCalled()
  })
})
