import { createPinia, setActivePinia } from "pinia";
import { beforeEach, expect, test, vi } from "vitest";

const { userRequest } = vi.hoisted(() => ({ userRequest: vi.fn() }));

vi.mock("@/api", () => ({
  accessAPI: {
    summary: vi.fn(),
    users: vi.fn(),
    user: userRequest,
    updateUser: vi.fn(),
    setTool: vi.fn(),
  },
}));

import { useAccessStore } from "./access";

beforeEach(() => {
  setActivePinia(createPinia());
  userRequest.mockReset();
});

test("clearSelection ignores a stale detail response", async () => {
  let resolveRequest: (value: {
    ok: true;
    status: number;
    data: { user?: { id: string } };
  }) => void = () => undefined;
  userRequest.mockReturnValue(
    new Promise((resolve) => {
      resolveRequest = resolve;
    }),
  );
  const store = useAccessStore();

  const pending = store.selectUser("user-a");
  store.clearSelection();
  resolveRequest({ ok: true, status: 200, data: { user: { id: "user-a" } } });
  await pending;

  expect(store.selectedUserId).toBeNull();
  expect(store.detail).toBeNull();
  expect(store.selectedUser).toBeNull();
  expect(store.detailLoading).toBe(false);
});
