/**
 * Farm AI Assistant API
 * GET context (farm bar data), POST chat (user message + optional farm_context/images).
 */

import { apiClient } from '../client'
import type { FarmContext } from '@views/dashboards/farm/farmAiAssistant/farmAiAssistantTypes'

const PREFIX = '/api/farm-ai-assistant'

export interface FarmContextResponse {
  soilType: string
  waterEC: string
  selectedCrop: string
  growthStage: string
  lastIrrigationStatus: string
}

export interface ChatSection {
  type: 'text' | 'list' | 'recommendation' | 'warning'
  title?: string
  content?: string
  items?: string[]
  icon?: 'droplet' | 'leaf' | 'warning' | 'fertilizer' | 'calendar'
  frequency?: string
  amount?: string
  timing?: string
  expandableExplanation?: string
}

export interface ChatPayload {
  content: string
  farm_context?: FarmContext
  images?: string[]
  conversation_id?: string
}

export interface ChatResponseData {
  message_id: string
  conversation_id: string
  content: string
  sections: ChatSection[]
}

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

function unwrap<T>(res: ApiResponse<T>): T {
  return res.data
}

export const farmAiAssistantService = {
  /**
   * Returns farm context for the context bar (soilType, waterEC, selectedCrop, growthStage, lastIrrigationStatus).
   */
  getContext(): Promise<FarmContextResponse> {
    return apiClient
      .get<ApiResponse<FarmContextResponse>>(`${PREFIX}/context/`)
      .then(unwrap)
  },

  /**
   * Send user message (and optional farm_context, images, conversation_id). Returns message with sections.
   */
  chat(payload: ChatPayload): Promise<ChatResponseData> {
    return apiClient
      .post<ApiResponse<ChatResponseData>>(`${PREFIX}/chat/`, payload)
      .then(unwrap)
  }
}
