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

use super::dto::*;
use compliance_core::models::TrackerIssue;

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

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

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