// useTelemetry Hook - Lógica de negócio para telemetria
// Encapsula toda a lógica de dados de telemetria

import { useState, useEffect, useCallback } from 'react';
import { telemetryService } from '../services/telemetryService';

export const useTelemetry = () => {
  const [vehicles, setVehicles] = useState([]);
  const [alerts, setAlerts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const fetchPositions = useCallback(async () => {
    try {
      setLoading(true);
      const data = await telemetryService.getVehiclePositions();
      setVehicles(data);
      
      const alertData = await telemetryService.getAlerts();
      setAlerts(alertData);
      
      setError(null);
    } catch (err) {
      setError(err.message);
      console.error('Erro ao buscar posições:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  const getVehicleHistory = useCallback(async (plate) => {
    try {
      return await telemetryService.getVehicleHistory(plate);
    } catch (err) {
      console.error('Erro ao buscar histórico:', err);
      return [];
    }
  }, []);

  const getVehicleByPlate = useCallback(async (plate) => {
    try {
      return await telemetryService.getVehicleByPlate(plate);
    } catch (err) {
      console.error('Erro ao buscar veículo:', err);
      return null;
    }
  }, []);

  useEffect(() => {
    fetchPositions();
    
    // Simula polling a cada 30 segundos
    const interval = setInterval(fetchPositions, 30000);
    
    return () => clearInterval(interval);
  }, [fetchPositions]);

  return {
    vehicles,
    alerts,
    loading,
    error,
    refresh: fetchPositions,
    getVehicleHistory,
    getVehicleByPlate
  };
};
