import type { GeoEvent, SensorLog, ApiConfig } from '../types';
import { sampleEvents, generateSensorData } from '../data/sampleData';

const defaultConfig: ApiConfig = {
  eventsEndpoint: '/api/events',
  sensorEndpoint: '/api/sensors',
  pollIntervalMs: 30_000,
};

let cachedSensorData: SensorLog[] | null = null;

export async function fetchEvents(_config?: Partial<ApiConfig>): Promise<GeoEvent[]> {  
  // In production, replace with actual API call:
  // const res = await fetch(config.eventsEndpoint);
  // return res.json();
  return Promise.resolve(sampleEvents);
}

export async function fetchSensorData(_config?: Partial<ApiConfig>): Promise<SensorLog[]> {  
  // In production, replace with actual API call:
  // const res = await fetch(config.sensorEndpoint);
  // return res.json();
  if (!cachedSensorData) {
    cachedSensorData = generateSensorData();
  }
  return Promise.resolve(cachedSensorData);
}

export function createPollingService(
  onEvents: (events: GeoEvent[]) => void,
  onSensors: (data: SensorLog[]) => void,
  config: Partial<ApiConfig> = {},
) {
  const merged = { ...defaultConfig, ...config };
  let intervalId: number | null = null;

  const poll = async () => {
    const [events, sensors] = await Promise.all([
      fetchEvents(merged),
      fetchSensorData(merged),
    ]);
    onEvents(events);
    onSensors(sensors);
  };

  return {
    start: () => {
      poll();
      intervalId = window.setInterval(poll, merged.pollIntervalMs);
    },
    stop: () => {
      if (intervalId !== null) {
        clearInterval(intervalId);
        intervalId = null;
      }
    },
  };
}
