// ── Traccar GPS API (via targo-hub proxy) ───────────────────────────────────
// All requests go through targo-hub which holds Traccar credentials server-side.
// No credentials in the frontend.
// ─────────────────────────────────────────────────────────────────────────────

import { HUB_URL } from 'src/config/hub'

let _devices = []

// ── Devices ──────────────────────────────────────────────────────────────────
export async function fetchDevices () {
  try {
    const res = await fetch(HUB_URL + '/traccar/devices')
    if (res.ok) {
      _devices = await res.json()
      return _devices
    }
  } catch {}
  return _devices
}

// ── Positions (batch via hub) ───────────────────────────────────────────────
export async function fetchPositions (deviceIds = null) {
  if (!deviceIds?.length) return []
  try {
    const res = await fetch(HUB_URL + '/traccar/positions?deviceIds=' + deviceIds.join(','))
    if (res.ok) return res.json()
  } catch {}
  return []
}

// ── Get position for a specific device ───────────────────────────────────────
export async function fetchDevicePosition (deviceId) {
  const positions = await fetchPositions([deviceId])
  return positions[0] || null
}

// ── Get all positions mapped by deviceId ─────────────────────────────────────
export async function fetchAllPositions () {
  if (!_devices.length) await fetchDevices()
  const deviceIds = _devices.filter(d => d.positionId).map(d => d.id)
  if (!deviceIds.length) return {}
  const positions = await fetchPositions(deviceIds)
  const map = {}
  positions.forEach(p => { map[p.deviceId] = p })
  return map
}

// ── Utility: match device to tech by uniqueId or name ────────────────────────
export function matchDeviceToTech (devices, techs) {
  const matched = []
  for (const tech of techs) {
    const traccarId = tech.traccarDeviceId
    if (!traccarId) continue
    const device = devices.find(d => d.id === parseInt(traccarId) || d.uniqueId === traccarId)
    if (device) matched.push({ tech, device })
  }
  return matched
}

// ── Session (for WebSocket — now via hub SSE or polling) ─────────────────────
export async function createTraccarSession () {
  // WebSocket not supported through hub proxy — use polling
  return false
}

export { _devices as cachedDevices }
