import { beforeEach, describe, expect, it, vi } from "vitest";
import { GET } from "./route";
import { ApiV1Error } from "@/lib/api-v1/errors";

const mocks = vi.hoisted(() => ({
  requireApiV1Auth: vi.fn(),
  getExtensionConversationContext: vi.fn(),
}));

vi.mock("@/lib/api-v1/auth", () => ({
  requireApiV1Auth: mocks.requireApiV1Auth,
}));

vi.mock("@/lib/api-v1/services/extension/extension-service", () => ({
  getExtensionConversationContext: mocks.getExtensionConversationContext,
}));

describe("GET /api/v1/extension/conversation-context", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("retorna contexto agregado da conversa", async () => {
    mocks.requireApiV1Auth.mockResolvedValue({
      supabase: {},
      user: { id: "user-1" },
    });
    mocks.getExtensionConversationContext.mockResolvedValue({
      data: {
        phone: "5511999999999",
        customer_found: true,
        customer: {
          id: "client-1",
          name: "Maria",
        },
        related_products: [
          {
            product_id: "prod-1",
            product_name: "Caneca",
          },
        ],
      },
    });

    const response = await GET(new Request("http://localhost/api/v1/extension/conversation-context?phone=5511999999999"));
    expect(response.status).toBe(200);
    await expect(response.json()).resolves.toMatchObject({
      success: true,
      data: {
        customer_found: true,
        related_products: [
          {
            product_id: "prod-1",
          },
        ],
      },
    });
  });

  it("valida telefone obrigatorio", async () => {
    mocks.requireApiV1Auth.mockResolvedValue({
      supabase: {},
      user: { id: "user-1" },
    });

    const response = await GET(new Request("http://localhost/api/v1/extension/conversation-context?phone="));
    expect(response.status).toBe(400);
    await expect(response.json()).resolves.toMatchObject({
      success: false,
      error: {
        code: "invalid_phone",
      },
    });
  });
});
