use dioxus::prelude::*;
use serde::{Deserialize, Serialize};

// ── Response types ──

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct HelpChatApiResponse {
    pub data: HelpChatResponseData,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct HelpChatResponseData {
    pub message: String,
}

// ── History message type ──

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HelpChatHistoryMessage {
    pub role: String,
    pub content: String,
}

// ── Server function ──

#[server]
pub async fn send_help_chat_message(
    message: String,
    history: Vec<HelpChatHistoryMessage>,
) -> Result<HelpChatApiResponse, ServerFnError> {
    let state: super::server_state::ServerState =
        dioxus_fullstack::FullstackContext::extract().await?;

    let url = format!("{}/api/v1/help/chat", state.agent_api_url);
    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(120))
        .build()
        .map_err(|e| ServerFnError::new(e.to_string()))?;

    let resp = client
        .post(&url)
        .json(&serde_json::json!({
            "message": message,
            "history": history,
        }))
        .send()
        .await
        .map_err(|e| ServerFnError::new(format!("Help chat request failed: {e}")))?;

    let text = resp
        .text()
        .await
        .map_err(|e| ServerFnError::new(format!("Failed to read response: {e}")))?;

    let body: HelpChatApiResponse = serde_json::from_str(&text)
        .map_err(|e| ServerFnError::new(format!("Failed to parse response: {e}")))?;

    Ok(body)
}
