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(),
  getExtensionCustomerContext: vi.fn(),
}));

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

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

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

  it("retorna contexto agregado do cliente", async () => {
    mocks.requireApiV1Auth.mockResolvedValue({
      supabase: {},
      user: { id: "user-1" },
    });
    mocks.getExtensionCustomerContext.mockResolvedValue({
      data: {
        phone: "5511999999999",
        customer_found: true,
        customer: {
          id: "client-1",
          name: "Maria",
        },
        recent_orders: [],
        recent_quotes: [],
      },
    });

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

  it("nega acesso sem token", async () => {
    mocks.requireApiV1Auth.mockRejectedValue(new ApiV1Error(401, "missing_bearer_token", "Token Bearer obrigatorio."));

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