const AI_SERVICE = process.env.AI_SERVICE_URL || "http://localhost:3001"

export async function chatWithAI(message: string, jwtToken: string) {
  const url = `${AI_SERVICE}/ai/chat`
  const body = JSON.stringify({ message })

  const res = await fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json", Authorization: `Bearer ${jwtToken}` },
    body,
  })

  const text = await res.text()

  if (!res.ok) {
    throw new Error(`AI error ${res.status}: ${text.substring(0, 200)}`)
  }

  const data = JSON.parse(text)
  return data.response || ""
}

export async function fetchJobs() {
  try {
    const res = await fetch(`${AI_SERVICE}/ai/jobs`)
    if (!res.ok) return []
    const data = await res.json()
    return data.jobs || []
  } catch {
    console.warn("Failed to fetch AI jobs")
    return []
  }
}

export async function checkAiServiceStatus() {
  try {
    const res = await fetch(`${AI_SERVICE}/health`)
    if (!res.ok) return false
    const data = await res.json()
    return data.status === "ok"
  } catch {
    console.warn("Failed to check AI service status")
    return false
  }
}
