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[]> {
  // 더미 모드: sampleEvents 반환
  return Promise.resolve(sampleEvents);
}

/** Backend DB에서 이벤트 범위 조회 (API 모드 리플레이용) */
export async function fetchEventsByRange(from: string, to: string): Promise<GeoEvent[]> {
  try {
    const res = await fetch(`/api/kcg/events?from=${from}&to=${to}`);
    if (!res.ok) return [];
    const data = await res.json();
    return (data.items ?? []).map((d: Record<string, unknown>) => ({
      id: String(d.id ?? ''),
      timestamp: Number(d.timestamp ?? 0),
      lat: Number(d.lat ?? 0),
      lng: Number(d.lng ?? 0),
      type: (String(d.type ?? 'alert')) as GeoEvent['type'],
      source: d.source ? String(d.source) as GeoEvent['source'] : undefined,
      label: String(d.label ?? ''),
      description: d.description ? String(d.description) : undefined,
      intensity: d.intensity != null ? Number(d.intensity) : undefined,
    }));
  } catch {
    return [];
  }
}

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;
      }
    },
  };
}
