// frontend/tests/connectors/api.test.ts — connectorsApi OAuth/providers 쿼리 구성
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { connectorsApi } from "@/lib/connectors/api";

function mockFetch(payload: unknown) {
  const fn = vi.fn().mockResolvedValue({
    ok: true,
    json: () => Promise.resolve(payload),
  });
  vi.stubGlobal("fetch", fn);
  return fn;
}

beforeEach(() => vi.restoreAllMocks());
afterEach(() => vi.unstubAllGlobals());

describe("connectorsApi", () => {
  it("oauthStart 는 domain/provider/redirect_after 를 인코딩해 호출", async () => {
    const fetchMock = mockFetch({ authorize_url: "https://x" });
    const res = await connectorsApi.oauthStart("mail", "outlook", "/settings?tab=mail");
    expect(res.authorize_url).toBe("https://x");
    const url = fetchMock.mock.calls[0][0] as string;
    expect(url).toContain("/api/connectors/oauth/start?");
    expect(url).toContain("domain=mail");
    expect(url).toContain("provider=outlook");
    expect(url).toContain("redirect_after=%2Fsettings%3Ftab%3Dmail");
  });

  it("providers 는 domain 필터 쿼리를 붙인다", async () => {
    const fetchMock = mockFetch([{ domain: "mail", provider: "gmail", label: "Gmail", configured: true }]);
    const rows = await connectorsApi.providers("mail");
    expect(rows[0].provider).toBe("gmail");
    expect(fetchMock.mock.calls[0][0]).toContain("/api/connectors/providers?domain=mail");
  });
});
