use crate::*;

const MAX_WIDGET_ROWS: u32 = 10;

#[uniffi::export(async_runtime = "tokio")]
impl GotchaCore {
    pub async fn widget_activity(
        &self,
        server_id: String,
        limit: u32,
    ) -> Result<WidgetActivityPage, GotchaError> {
        let server = self.server_by_id(&server_id)?;
        let mut rows = activity_rows(&load_activities(&server, 1).await?.items);
        rows.truncate(widget_limit(limit)?);
        Ok(WidgetActivityPage {
            server_name: server.name,
            rows,
        })
    }

    pub async fn widget_pulls(
        &self,
        server_id: String,
        limit: u32,
    ) -> Result<WidgetPullPage, GotchaError> {
        let server = self.server_by_id(&server_id)?;
        let pulls = load_pulls(&server, "open", "", "", 1).await?;
        let mut rows = pull_rows(&pulls.items);
        rows.truncate(widget_limit(limit)?);
        Ok(WidgetPullPage {
            server_name: server.name,
            rows,
        })
    }
}

fn widget_limit(limit: u32) -> Result<usize, GotchaError> {
    (1..=MAX_WIDGET_ROWS)
        .contains(&limit)
        .then_some(limit as usize)
        .ok_or_else(|| "Widget row count must be between 1 and 10.".into())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn validates_widget_row_limits() {
        assert_eq!(widget_limit(1).unwrap(), 1);
        assert_eq!(widget_limit(10).unwrap(), 10);
        assert!(widget_limit(0).is_err());
        assert!(widget_limit(11).is_err());
    }
}
