import { authStorage } from "./auth-storage";

const BASE_API_URL =
  (import.meta as { env?: Record<string, string> }).env?.[
    "VITE_BASE_API_URL"
  ] ?? "http://localhost:3001/api";

interface RefreshResponse {
  token: string;
  refreshToken: string;
}

export async function refreshAccessToken(): Promise<string> {
  const refreshToken = authStorage.getRefreshToken();
  if (!refreshToken) throw new Error("No refresh token available");

  // The IAM service exposes this as `refresh-token`; posting to `/auth/refresh`
  // 404s, which the catch below turns into a silent logout.
  const response = await fetch(`${BASE_API_URL}/auth/refresh-token`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ refreshToken }),
  });

  if (!response.ok) {
    authStorage.clear();
    throw new Error("Token refresh failed");
  }

  const data: RefreshResponse = await response.json();
  authStorage.setToken(data.token);
  if (data.refreshToken) authStorage.setRefreshToken(data.refreshToken);
  return data.token;
}
