import { afterEach, describe, expect, it, vi } from "vitest";

import { fetchFacebookUserData } from "../facebook-graph";

describe("fetchFacebookUserData", () => {
  afterEach(() => {
    vi.unstubAllGlobals();
  });

  it("requests profile data without requesting or returning email", async () => {
    const fetchMock = vi.fn().mockResolvedValue(
      new Response(
        JSON.stringify({
          id: "facebook-1",
          name: "Elio",
          email: "should-not-be-used@example.com",
          picture: {
            data: { url: "https://example.com/avatar.jpg" },
          },
        }),
        {
          status: 200,
          headers: { "content-type": "application/json" },
        },
      ),
    );
    vi.stubGlobal("fetch", fetchMock);

    const result = await fetchFacebookUserData("access-token");
    const requestUrl = new URL(String(fetchMock.mock.calls[0]?.[0]));

    expect(requestUrl.searchParams.get("fields")).toBe(
      "id,name,picture.type(large)",
    );
    expect(requestUrl.searchParams.get("fields")).not.toContain("email");
    expect(requestUrl.searchParams.get("access_token")).toBe("access-token");
    expect(result).toEqual({
      success: true,
      data: {
        id: "facebook-1",
        name: "Elio",
        pictureUrl: "https://example.com/avatar.jpg",
      },
    });
    if (result.success) expect(result.data).not.toHaveProperty("email");
  });
});
