/**
 * Decode a VIN using the Cardog API
 * Requires NEXT_PUBLIC_CARDOG_API_URL and NEXT_PUBLIC_CARDOG_API_KEY
 */
export async function decodeAPI(vin: string) {
  const apiUrl = process.env.NEXT_PUBLIC_CARDOG_API_URL;
  const apiKey = process.env.NEXT_PUBLIC_CARDOG_API_KEY;

  if (!apiUrl) {
    throw new Error("NEXT_PUBLIC_CARDOG_API_URL is not configured");
  }

  const headers: Record<string, string> = {
    "Content-Type": "application/json",
  };

  // Add API key if configured
  if (apiKey) {
    headers["Authorization"] = `Bearer ${apiKey}`;
  }

  const response = await fetch(`${apiUrl}/vin/corgi/${vin}`, {
    headers,
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ error: "Unknown error" }));
    throw new Error(error.error || `API request failed: ${response.statusText}`);
  }

  return response.json();
}

/**
 * Check if API decoding is configured
 */
export function isAPIConfigured() {
  return !!process.env.NEXT_PUBLIC_CARDOG_API_URL;
}
