import { afterEach, expect, test, vi } from "vitest";
import { setSelectedAppCode } from "@/shared/api/request";
import { getDashboardUserProfileOverview } from "./api";

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

test("requests the app-scoped user profile overview with the current day range and time zone", async () => {
  setSelectedAppCode("huwaa");
  const payload = {
    activeUsers: 48,
    appCode: "huwaa",
    appVersionDistribution: [{ count: 30, key: "2.1.0", label: "2.1.0" }],
    genderDistribution: [{ count: 32, key: "female", label: "女" }],
    newUsers: 7,
    totalUsers: 120,
    updatedAtMs: 1783728000000
  };
  vi.stubGlobal(
    "fetch",
    vi.fn(async () => new Response(JSON.stringify({ code: 0, data: payload })))
  );

  const result = await getDashboardUserProfileOverview({
    appCode: "huwaa",
    endMs: 1783728000000,
    startMs: 1783699200000,
    statTz: "Asia/Shanghai"
  });
  const [input, init] = vi.mocked(fetch).mock.calls[0];
  const url = new URL(String(input));

  expect(url.pathname).toBe("/api/v1/dashboard/user-profile-overview");
  expect(Object.fromEntries(url.searchParams)).toEqual({
    app_code: "huwaa",
    end_ms: "1783728000000",
    start_ms: "1783699200000",
    stat_tz: "Asia/Shanghai"
  });
  expect(init?.headers).toMatchObject({ "X-App-Code": "huwaa" });
  expect(result).toEqual(payload);
});
