/**
 * Sensor Hub Service
 * Handles sensor hub API calls
 */

import { apiClient } from '../client'

export interface Sensor {
  name: string
  uuid_sensor: string
  last_updated: string
  [key: string]: unknown
}

export interface ListSensorsResponse {
  status?: string
  data: Sensor | Sensor[]
}

export interface AddSensorPayload {
  name: string
  uuid_sensor: string
  area_geojson?: Record<string, unknown>
  area_m2?: number
}

export const sensorHubService = {
  /**
   * Add a new sensor
   */
  async addSensor(payload: AddSensorPayload): Promise<Sensor> {
    const response = await apiClient.post<{ data?: Sensor }>('/api/sensor-hub/', payload)

    return (response?.data as Sensor) ?? (payload as unknown as Sensor)
  },

  /**
   * Get list of sensors
   */
  async listSensors(): Promise<Sensor[]> {
    const response = await apiClient.get<ListSensorsResponse>('/api/sensor-hub/')
    const data = response?.data

    if (Array.isArray(data)) {
      return data
    }

    if (data && typeof data === 'object') {
      return [data as Sensor]
    }

    return []
  }
}
