import assert from "node:assert/strict";
import { test } from "node:test";
import { AxiosError } from "axios";
import apiClient from "@/lib/api/client";
import { useAuthStore, type User } from "@/store/authStore";

const user = (id: number) => ({ id, auth_token: `test-token-${id}`, user_type: "volunteer" }) as User;

test("a late 401 from the signed-out account cannot end the promoted session", async () => {
  const original = apiClient.defaults.adapter;
  let rejectRequest!: () => void;
  apiClient.defaults.adapter = config => new Promise((_, reject) => {
    rejectRequest = () => reject(new AxiosError("Unauthorized", "ERR_BAD_REQUEST", config, undefined,
      { status: 401, statusText: "Unauthorized", data: {}, headers: {}, config }));
  });
  try {
    useAuthStore.setState({ user: user(1), accounts: [user(2)] });
    const pending = apiClient.get("/account/").catch(error => error);
    await new Promise(resolve => setImmediate(resolve));
    useAuthStore.getState().signOutActiveAccount();
    rejectRequest();
    await pending;
    assert.equal(useAuthStore.getState().user?.id, 2);
    useAuthStore.getState().signOutActiveAccount();
    assert.equal(useAuthStore.getState().user, null);
    assert.deepEqual(useAuthStore.getState().accounts, []);
  } finally {
    apiClient.defaults.adapter = original;
    useAuthStore.setState({ user: null, accounts: [] });
  }
});

test("a 401 for the current account still ends its session", async () => {
  const original = apiClient.defaults.adapter;
  apiClient.defaults.adapter = async config => {
    throw new AxiosError("Unauthorized", "ERR_BAD_REQUEST", config, undefined,
      { status: 401, statusText: "Unauthorized", data: {}, headers: {}, config });
  };
  try {
    useAuthStore.setState({ user: user(1), accounts: [user(2)] });
    await assert.rejects(apiClient.get("/account/"));
    assert.equal(useAuthStore.getState().user, null);
    assert.equal(useAuthStore.getState().accounts[0].id, 2);
  } finally {
    apiClient.defaults.adapter = original;
    useAuthStore.setState({ user: null, accounts: [] });
  }
});
