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

import { apiClient } from '../client'

const PREFIX = '/api/fertilization-recommendation'

export interface FarmData {
  soilType: string
  organicMatter: string
  waterEC: string
}

export interface GrowthStage {
  id: string
  icon: string
}

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

export interface FertilizationConfigResponse {
  farmData: FarmData
  growthStages: GrowthStage[]
  cropOptions: CropOption[]
}

export interface FertilizationPlan {
  npkRatio: string
  amountPerHectare: string
  applicationMethod: string
  applicationInterval: string
  reasoning: string
}

export interface FertilizationRecommendPayload {
  crop_id?: string
  growth_stage?: string
  soilType?: string
  organicMatter?: string
  waterEC?: 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 fertilizationRecommendationService = {
  getConfig(): Promise<FertilizationConfigResponse> {
    return unwrap(apiClient.get<ApiResponse<FertilizationConfigResponse>>(`${PREFIX}/config/`))
  },

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