/**
 * Silent access-token refresh for the client fetch layer. On a 401, `clientFetch` calls this
 * once to rotate the token pair (the server does rotation + reuse-detection) and, on success,
 * retries the original request. A module-level single-flight promise coalesces concurrent 401s
 * into one refresh so a burst of parallel requests rotates the session exactly once.
 *
 * This is deliberately a bare `fetch` (not `clientFetch`, not the `services/auth` client) to
 * avoid an import cycle — it only shares the token-cookie writers in `@/lib/auth/session`.
 */
import { API_URL } from '@/config';
import { COOKIE_NAMES } from '@/lib/cookies';
import { getClientCookie } from '@/lib/cookies/client';
import { clearAuthTokens, persistAuthTokens } from '@/lib/auth/session';

const REFRESH_PATH = '/api/v1/auth/refresh';

let inFlight: Promise<boolean> | null = null;

async function doRefresh(): Promise<boolean> {
  const refreshToken = getClientCookie(COOKIE_NAMES.REFRESH_TOKEN);
  if (!refreshToken) return false;

  try {
    const response = await fetch(`${API_URL}${REFRESH_PATH}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ refreshToken }),
    });
    if (!response.ok) {
      // 401 here means an unknown/expired/reused (stolen) token — the session is gone.
      clearAuthTokens();
      return false;
    }
    const envelope = await response.json();
    const tokens = envelope?.data;
    if (!tokens?.accessToken || !tokens?.refreshToken) {
      clearAuthTokens();
      return false;
    }
    persistAuthTokens(tokens);
    return true;
  } catch {
    return false;
  }
}

export function attemptTokenRefresh(): Promise<boolean> {
  if (!inFlight) {
    inFlight = doRefresh().finally(() => {
      inFlight = null;
    });
  }
  return inFlight;
}
