/**
 * Irrigation Recommendation API
 * @see RECOMMENDATION_APIS.md
 */

import { apiClient } from '../client'

const PREFIX = '/api/irrigation-recommendation'

export interface FarmInfo {
  soilType: string
  waterQuality: string
  climateZone: string
}

export interface CropOption {
  id: string
  labelKey: string
  icon: string
}

export interface IrrigationConfigResponse {
  farmInfo: FarmInfo
  cropOptions: CropOption[]
}

export interface IrrigationPlan {
  frequencyPerWeek: number
  durationMinutes: number
  bestTimeOfDay: string
  moistureLevel: number
  warning?: string
}

export interface IrrigationRecommendPayload {
  crop_id?: string
  soilType?: string
  waterQuality?: string
  climateZone?: string
}

interface ApiResponse<T> {
  status: string
  data: T
}

async function unwrap<T>(promise: Promise<ApiResponse<T>>): Promise<T> {
  const res = await promise
  return res.data
}

export const irrigationRecommendationService = {
  getConfig(): Promise<IrrigationConfigResponse> {
    return unwrap(apiClient.get<ApiResponse<IrrigationConfigResponse>>(`${PREFIX}/config/`))
  },

  recommend(payload?: IrrigationRecommendPayload): Promise<{ plan: IrrigationPlan }> {
    return unwrap(apiClient.post<ApiResponse<{ plan: IrrigationPlan }>>(`${PREFIX}/recommend/`, payload ?? {}))
  },
}
