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

use compliance_core::models::ScanRun;

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ScansListResponse {
    pub data: Vec<ScanRun>,
    pub total: Option<u64>,
    pub page: Option<u64>,
}

#[server]
pub async fn fetch_scan_runs(page: u64) -> Result<ScansListResponse, ServerFnError> {
    let state: super::server_state::ServerState =
        dioxus_fullstack::FullstackContext::extract().await?;
    let url = format!(
        "{}/api/v1/scan-runs?page={page}&limit=20",
        state.agent_api_url
    );

    let resp = reqwest::get(&url)
        .await
        .map_err(|e| ServerFnError::new(e.to_string()))?;
    let body: ScansListResponse = resp
        .json()
        .await
        .map_err(|e| ServerFnError::new(e.to_string()))?;
    Ok(body)
}
