import { API_BASE_URL } from "./config";

/**
 * BE-135 — `POST /logout/` revokes the token it is called with, so a signed-out
 * token stops working on the server too instead of living out its 1 / 30 days.
 *
 * Deliberately not `apiClient`:
 *  - each call carries its **own** account's token, while the axios interceptor
 *    injects the *active* user's — and the store has usually moved on by now;
 *  - a 401 here (token already expired or revoked) must not reach the client's
 *    401 → `endSession()` handler, which would end the session the reader just
 *    switched to.
 *
 * Fire-and-forget with `keepalive`, so the request survives the full-page
 * navigation that follows a sign-out. Failures are ignored: the token is gone
 * from this device either way.
 */
export function revokeSessionTokens(tokens: Array<string | null | undefined>): void {
  const unique = Array.from(new Set(tokens.filter((token): token is string => Boolean(token))));
  for (const token of unique) {
    void fetch(`${API_BASE_URL}/logout/`, {
      method: "POST",
      headers: { Authorization: `Token ${token}`, Accept: "application/json" },
      keepalive: true,
    }).catch(() => undefined);
  }
}
