import { SeedConfig } from '../shared/types';

export async function fetchFullConfig(seed: SeedConfig): Promise<any> {
  const apiUrls = [
    seed.onsite_api_base_url,
    seed.primary_api_base_url,
    seed.backup_api_base_url
  ].filter(url => url !== null && url !== undefined) as string[];

  let lastError: any = null;

  for (const baseUrl of apiUrls) {
    try {
      console.log(`Bootstrap: Attempting connection to ${baseUrl}...`);

      // --- STEP 1: Get Device Config ---
      const deviceUrl = `${baseUrl}/v3/crud/event_device/${seed.event_device_id}`;
      const deviceResponse = await fetch(deviceUrl, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'x-aether-api-key': seed.aether_api_key,
          'x-no-account-id': 'bypass'
        },
      });

      if (!deviceResponse.ok) {
        throw new Error(`Device lookup failed (${deviceResponse.status})`);
      }

      const deviceResult = await deviceResponse.json();
      const deviceData = deviceResult.data || deviceResult;

      // Use 'app_base_url' as the FQDN for the site lookup
      const fqdn = deviceData.app_base_url || 'native-demo.oneskyit.com';

      // --- STEP 2: Get Site Context ---
      const searchUrl = `${baseUrl}/v3/crud/site_domain/search?limit=1`;
      const siteResponse = await fetch(searchUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-aether-api-key': seed.aether_api_key,
          'x-account-id': deviceData.account_id_random || deviceData.account_id || ''
        },
        body: JSON.stringify({
          and: [{ field: 'fqdn', op: 'eq', value: fqdn }]
        })
      });

      if (!siteResponse.ok) {
        throw new Error(`Site context lookup failed (${siteResponse.status})`);
      }

      const siteResult = await siteResponse.json();
      const siteDomain = (siteResult.data && siteResult.data.length > 0) ? siteResult.data[0] : null;

      console.log(`Bootstrap Success using ${baseUrl}`);

      return {
        ...siteDomain,
        native_device: deviceData,
        aether_api_key: seed.aether_api_key // Include the key for frontend use
      };

    } catch (error) {
      console.warn(`Bootstrap failed for ${baseUrl}: `, error);
      lastError = error;
      continue; // Try next URL
    }
  }

  console.error('Bootstrap Critical Failure: All API endpoints exhausted.', lastError);
  return null;
}
