const API_BASE = import.meta.env.VITE_API_URL || '/api/v1'

async function request<T>(endpoint: string, options?: RequestInit): Promise<T> {
  const response = await fetch(`${API_BASE}${endpoint}`, {
    headers: { 'Content-Type': 'application/json' },
    ...options,
  })
  if (!response.ok) {
    throw new Error(`API error: ${response.status} ${response.statusText}`)
  }
  return response.json()
}

export const api = {
  /** GET /api/v1/cameras — list all cameras with latest status */
  getCameras: () => request<import('../types').CameraStatus[]>('/cameras'),

  /** GET /api/v1/cameras/{id} — full detail + 24h history */
  getCameraDetail: (id: string) =>
    request<import('../types').CameraDetail>(`/cameras/${id}`),

  /** POST /api/v1/cameras/{id}/start — start recording */
  startRecording: (cameraId: string) =>
    request<import('../types').StartStopResponse>(`/cameras/${cameraId}/start`, {
      method: 'POST',
    }),

  /** POST /api/v1/cameras/{id}/stop — stop recording */
  stopRecording: (cameraId: string) =>
    request<import('../types').StartStopResponse>(`/cameras/${cameraId}/stop`, {
      method: 'POST',
    }),
}
