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

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct NotificationListResponse {
    pub data: Vec<CveNotificationData>,
    #[serde(default)]
    pub total: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CveNotificationData {
    #[serde(rename = "_id")]
    pub id: Option<serde_json::Value>,
    pub cve_id: String,
    pub repo_name: String,
    pub package_name: String,
    pub package_version: String,
    pub severity: String,
    pub cvss_score: Option<f64>,
    pub summary: Option<String>,
    pub url: Option<String>,
    pub status: String,
    #[serde(default)]
    pub created_at: Option<serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct NotificationCountResponse {
    pub count: u64,
}

#[server]
pub async fn fetch_notification_count() -> Result<u64, ServerFnError> {
    let resp = super::agent_client::agent_get("/api/v1/notifications/count")
        .await?
        .send()
        .await
        .map_err(|e| ServerFnError::new(e.to_string()))?;
    let body: NotificationCountResponse = resp
        .json()
        .await
        .map_err(|e| ServerFnError::new(e.to_string()))?;
    Ok(body.count)
}

#[server]
pub async fn fetch_notifications() -> Result<NotificationListResponse, ServerFnError> {
    let resp = super::agent_client::agent_get("/api/v1/notifications?limit=20")
        .await?
        .send()
        .await
        .map_err(|e| ServerFnError::new(e.to_string()))?;
    let body: NotificationListResponse = resp
        .json()
        .await
        .map_err(|e| ServerFnError::new(e.to_string()))?;
    Ok(body)
}

#[server]
pub async fn mark_all_notifications_read() -> Result<(), ServerFnError> {
    super::agent_client::agent_request(reqwest::Method::POST, "/api/v1/notifications/read-all")
        .await?
        .send()
        .await
        .map_err(|e| ServerFnError::new(e.to_string()))?;
    Ok(())
}

#[server]
pub async fn dismiss_notification(id: String) -> Result<(), ServerFnError> {
    super::agent_client::agent_request(
        reqwest::Method::PATCH,
        &format!("/api/v1/notifications/{id}/dismiss"),
    )
    .await?
    .send()
    .await
    .map_err(|e| ServerFnError::new(e.to_string()))?;
    Ok(())
}
