/**
 * Decoupled Client for the Standalone Atiku 2027 Situation Room Backend REST API
 * Supports both local microservice mode (http://localhost:5001) and production backend deployment.
 */

const DEFAULT_API_URL = typeof window !== 'undefined'
  ? (process.env.NEXT_PUBLIC_API_URL || `${window.location.origin}/api/v1`)
  : (process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5001/api/v1');

export const API_BASE_URL = DEFAULT_API_URL;
export const API_KEY = process.env.NEXT_PUBLIC_API_KEY || 'ATIKU2027_LIVE_PU_AGENT_KEY';

export async function fetchFromBackend(endpoint: string, options: RequestInit = {}) {
  const url = endpoint.startsWith('http') ? endpoint : `${API_BASE_URL}${endpoint.startsWith('/') ? '' : '/'}${endpoint}`;
  
  const headers = new Headers(options.headers || {});
  if (!headers.has('Content-Type') && !(options.body instanceof FormData)) {
    headers.set('Content-Type', 'application/json');
  }
  if (!headers.has('X-API-Key')) {
    headers.set('X-API-Key', API_KEY);
  }

  const res = await fetch(url, {
    ...options,
    headers,
  });

  return res;
}

export async function submitPuResultToBackend(payload: any) {
  const res = await fetchFromBackend('/results', {
    method: 'POST',
    body: JSON.stringify(payload),
  });
  return res.json();
}

export async function lookupPuInBackend(puCode: string) {
  const res = await fetchFromBackend(`/pu/lookup?pu_code=${encodeURIComponent(puCode)}`);
  return res.json();
}

export async function reportIncidentToBackend(incident: any) {
  const res = await fetchFromBackend('/incidents', {
    method: 'POST',
    body: JSON.stringify(incident),
  });
  return res.json();
}
