// API Endpoint Configuration with Domain Fallbacks
// Primary: nithic.ai, Fallbacks: nithic.com, nithic.io, nithic.net, nithic.org, nithic.info

const DOMAINS = [
  'nithic.ai',
  'nithic.com',
  'nithic.io',
  'nithic.net',
  'nithic.org',
  'nithic.info'
];

export const API_ENDPOINTS = {
  ruleApi:    DOMAINS.map(d => `https://api.${d}`),
  cloudApi:   DOMAINS.map(d => `https://cloud.${d}`),
  portalApi:  DOMAINS.map(d => `https://api.portal.${d}`)
};

// Default primary endpoints
export const DEFAULT_RULE_API_URL    = API_ENDPOINTS.ruleApi[0];    // https://api.nithic.ai
export const DEFAULT_CLOUD_API_URL   = API_ENDPOINTS.cloudApi[0];   // https://cloud.nithic.ai
export const DEFAULT_PORTAL_API_URL  = API_ENDPOINTS.portalApi[0];  // https://api.portal.nithic.ai

/**
 * Try a fetch across fallback domains until one succeeds
 * @param {string[]} urls - Array of base URLs to try
 * @param {string} path - API path to append
 * @param {RequestInit} options - Fetch options
 * @param {number} timeoutMs - Per-request timeout
 * @returns {Promise<Response>}
 */
export async function fetchWithFallback(urls, path, options = {}, timeoutMs = 5000) {
  let lastError;
  for (const baseUrl of urls) {
    try {
      const controller = new AbortController();
      const timer = setTimeout(() => controller.abort(), timeoutMs);
      const response = await fetch(`${baseUrl}${path}`, {
        ...options,
        signal: controller.signal
      });
      clearTimeout(timer);
      if (response.ok || response.status < 500) {
        return response;
      }
      lastError = new Error(`${baseUrl}${path} returned ${response.status}`);
    } catch (err) {
      lastError = err;
    }
  }
  throw lastError;
}
