import { afterEach, expect, test, vi } from "vitest";
import { setAccessToken } from "@/shared/api/request";
import { createTeam, listOperationUsers, listTeams, listTeamUsers, OPERATION_TEAM_ID, updateTeam } from "./api";

afterEach(() => {
  setAccessToken("");
  vi.unstubAllGlobals();
});

test("team APIs use generated endpoint paths", async () => {
  vi.stubGlobal(
    "fetch",
    vi.fn(async () => new Response(JSON.stringify({ code: 0, data: [] })))
  );

  await listTeams({ keyword: "运营" });
  await createTeam({ description: "平台运营", name: "运营一部", parentId: 2, sort: 2 });
  await updateTeam(2, { description: "平台运营", name: "运营团队", parentId: null, sort: 2 });

  const calls = vi.mocked(fetch).mock.calls;
  expect(String(calls[0][0])).toContain("/api/v1/teams?");
  expect(String(calls[0][0])).toContain("keyword=%E8%BF%90%E8%90%A5");
  expect(calls[0][1]?.method).toBe("GET");
  expect(String(calls[1][0])).toContain("/api/v1/teams");
  expect(calls[1][1]?.method).toBe("POST");
  expect(JSON.parse(String(calls[1][1]?.body))).toEqual({ description: "平台运营", name: "运营一部", parentId: 2, sort: 2 });
  expect(String(calls[2][0])).toContain("/api/v1/teams/2");
  expect(calls[2][1]?.method).toBe("PATCH");
});

test("operation users are loaded from operation team id 2", async () => {
  vi.stubGlobal(
    "fetch",
    vi.fn(async () => new Response(JSON.stringify({ code: 0, data: { items: [], page: 1, pageSize: 50, total: 0 } })))
  );

  await listTeamUsers(1);
  await listOperationUsers({ status: "active" });

  const calls = vi.mocked(fetch).mock.calls;
  expect(OPERATION_TEAM_ID).toBe(2);
  expect(String(calls[0][0])).toContain("/api/v1/teams/1/users");
  expect(String(calls[1][0])).toContain("/api/v1/teams/2/users?");
  expect(String(calls[1][0])).toContain("status=active");
});
