import { AxiosError, AxiosHeaders } from "axios";
import { describe, expect, it } from "vitest";
import { isAuthQueryError } from "./client";
import { applyPollJitter } from "@/shared/config/polling";

describe("isAuthQueryError", () => {
  it("returns true for 401/403 Axios errors", () => {
    const err401 = new AxiosError("Unauthorized", AxiosError.ERR_BAD_REQUEST, undefined, undefined, {
      status: 401,
      data: {},
      statusText: "Unauthorized",
      headers: {},
      config: { headers: new AxiosHeaders() },
    });
    expect(isAuthQueryError(err401)).toBe(true);

    const err403 = new AxiosError("Forbidden", AxiosError.ERR_BAD_REQUEST, undefined, undefined, {
      status: 403,
      data: {},
      statusText: "Forbidden",
      headers: {},
      config: { headers: new AxiosHeaders() },
    });
    expect(isAuthQueryError(err403)).toBe(true);
  });

  it("returns false for other errors", () => {
    expect(isAuthQueryError(new Error("network"))).toBe(false);
    expect(isAuthQueryError({ status: 500, message: "x" })).toBe(false);
  });
});

describe("applyPollJitter", () => {
  it("keeps interval roughly within ±10%", () => {
    const ms = 10_000;
    for (let i = 0; i < 20; i++) {
      const j = applyPollJitter(ms);
      expect(j).toBeGreaterThanOrEqual(9000);
      expect(j).toBeLessThanOrEqual(11000);
    }
  });
});
