import { afterEach, expect, test, vi } from "vitest";
import { setAccessToken } from "@/shared/api/request";
import { listUsers, updateUserStatus } from "./api";

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

test("listUsers uses generated endpoint path and query", async () => {
  vi.stubGlobal(
    "fetch",
    vi.fn(async () => new Response(JSON.stringify({ code: 0, data: { items: [], page: 1, pageSize: 10, total: 0 } })))
  );

  const result = await listUsers({ page: 1, page_size: 10, status: "active" });
  const [url, init] = vi.mocked(fetch).mock.calls[0];

  expect(result.items).toEqual([]);
  expect(String(url)).toContain("/api/v1/users?");
  expect(String(url)).toContain("page=1");
  expect(String(url)).toContain("page_size=10");
  expect(String(url)).toContain("status=active");
  expect(init?.method).toBe("GET");
});

test("updateUserStatus sends generated endpoint path and payload", async () => {
  vi.stubGlobal(
    "fetch",
    vi.fn(async () => new Response(JSON.stringify({ code: 0, data: { id: 7, name: "张三", account: "zhangsan", status: "locked" } })))
  );

  await updateUserStatus(7, "locked");
  const [url, init] = vi.mocked(fetch).mock.calls[0];

  expect(String(url)).toContain("/api/v1/users/7/status");
  expect(init?.method).toBe("PATCH");
  expect(JSON.parse(String(init?.body))).toEqual({ status: "locked" });
});
