//! CAE signal operations.

use crate::zeroid::{
    client::{parse_api_error, ZeroIDClient},
    error::ZeroIDError,
    types::{CAESignal, IngestSignalRequest, SignalList},
};

/// Signals resource — ingest and list on `/api/v1/signals`.
pub struct SignalsResource<'a> {
    pub(crate) client: &'a ZeroIDClient,
}

impl<'a> SignalsResource<'a> {
    /// Ingest a CAE signal.
    ///
    /// `POST /api/v1/signals/ingest`
    pub async fn ingest(&self, request: &IngestSignalRequest) -> Result<CAESignal, ZeroIDError> {
        let body = serde_json::to_value(request)?;
        let headers = self.client.admin_headers();
        let resp = self
            .client
            .send_with_retry(
                reqwest::Method::POST,
                "/api/v1/signals/ingest",
                headers,
                Some(&body),
            )
            .await?;
        if !resp.status().is_success() {
            return Err(parse_api_error(resp).await);
        }
        Ok(resp.json().await?)
    }

    /// List recent signals.
    ///
    /// `GET /api/v1/signals`
    pub async fn list(&self) -> Result<SignalList, ZeroIDError> {
        let headers = self.client.admin_headers();
        let resp = self
            .client
            .send_with_retry(reqwest::Method::GET, "/api/v1/signals", headers, None)
            .await?;
        if !resp.status().is_success() {
            return Err(parse_api_error(resp).await);
        }
        Ok(resp.json().await?)
    }
}
