use axum::extract::{Extension, Query};
use axum::Json;
use mongodb::bson::doc;

use super::dto::*;
use compliance_core::models::ScanRun;
use compliance_core::tenant_ctx::TenantCtx;

#[tracing::instrument(skip_all)]
pub async fn list_scan_runs(
    Extension(agent): AgentExt,
    tenant: TenantCtx,
    Query(params): Query<PaginationParams>,
) -> ApiResult<Vec<ScanRun>> {
    let db = tenant_db(&agent, &tenant).await?;
    let db = &db;
    let skip = (params.page.saturating_sub(1)) * params.limit as u64;
    let total = db.scan_runs().count_documents(doc! {}).await.unwrap_or(0);

    let scans = match db
        .scan_runs()
        .find(doc! {})
        .sort(doc! { "started_at": -1 })
        .skip(skip)
        .limit(params.limit)
        .await
    {
        Ok(cursor) => collect_cursor_async(cursor).await,
        Err(e) => {
            tracing::warn!("Failed to fetch scan runs: {e}");
            Vec::new()
        }
    };

    Ok(Json(ApiResponse {
        data: scans,
        total: Some(total),
        page: Some(params.page),
    }))
}
