mockforge-http 0.3.116

HTTP/REST protocol support for MockForge
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
//! Drift budget and incident management handlers
//!
//! This module provides HTTP handlers for managing drift budgets and incidents.

use axum::{
    extract::{Path, Query, State},
    http::StatusCode,
    response::Json,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;

use chrono;
use mockforge_core::contract_drift::{DriftBudget, DriftBudgetEngine};
use mockforge_core::incidents::types::DriftIncident;
use mockforge_core::incidents::{
    IncidentManager, IncidentQuery, IncidentSeverity, IncidentStatus, IncidentType,
};

/// State for drift budget handlers
#[derive(Clone)]
pub struct DriftBudgetState {
    /// Drift budget engine
    pub engine: Arc<DriftBudgetEngine>,
    /// Incident manager
    pub incident_manager: Arc<IncidentManager>,
    /// GitOps handler (optional)
    pub gitops_handler: Option<Arc<mockforge_core::drift_gitops::DriftGitOpsHandler>>,
}

/// Request to create or update a drift budget
#[derive(Debug, Deserialize, Serialize)]
pub struct CreateDriftBudgetRequest {
    /// Endpoint path
    pub endpoint: String,
    /// HTTP method
    pub method: String,
    /// Maximum breaking changes allowed
    pub max_breaking_changes: Option<u32>,
    /// Maximum non-breaking changes allowed
    pub max_non_breaking_changes: Option<u32>,
    /// Severity threshold
    pub severity_threshold: Option<String>,
    /// Whether enabled
    pub enabled: Option<bool>,
    /// Workspace ID (optional)
    pub workspace_id: Option<String>,
}

/// Response for drift budget operations
#[derive(Debug, Serialize)]
pub struct DriftBudgetResponse {
    /// Budget ID
    pub id: String,
    /// Endpoint
    pub endpoint: String,
    /// Method
    pub method: String,
    /// Budget configuration
    pub budget: DriftBudget,
    /// Workspace ID
    pub workspace_id: Option<String>,
}

/// Request to query incidents
#[derive(Debug, Deserialize)]
pub struct ListIncidentsRequest {
    /// Filter by status
    pub status: Option<String>,
    /// Filter by severity
    pub severity: Option<String>,
    /// Filter by endpoint
    pub endpoint: Option<String>,
    /// Filter by method
    pub method: Option<String>,
    /// Filter by incident type
    pub incident_type: Option<String>,
    /// Filter by workspace ID
    pub workspace_id: Option<String>,
    /// Limit results
    pub limit: Option<usize>,
    /// Offset for pagination
    pub offset: Option<usize>,
}

/// Response for listing incidents
#[derive(Debug, Serialize)]
pub struct ListIncidentsResponse {
    /// List of incidents
    pub incidents: Vec<DriftIncident>,
    /// Total count
    pub total: usize,
}

/// Request to update incident status
#[derive(Debug, Deserialize)]
pub struct UpdateIncidentRequest {
    /// New status
    pub status: Option<String>,
    /// External ticket ID
    pub external_ticket_id: Option<String>,
    /// External ticket URL
    pub external_ticket_url: Option<String>,
}

/// Request to resolve incident
#[derive(Debug, Deserialize)]
pub struct ResolveIncidentRequest {
    /// Optional resolution note
    pub note: Option<String>,
}

/// Create or update a drift budget
///
/// POST /api/v1/drift/budgets
pub async fn create_budget(
    State(_state): State<DriftBudgetState>,
    Json(request): Json<CreateDriftBudgetRequest>,
) -> Result<Json<DriftBudgetResponse>, StatusCode> {
    let budget = DriftBudget {
        max_breaking_changes: request.max_breaking_changes.unwrap_or(0),
        max_non_breaking_changes: request.max_non_breaking_changes.unwrap_or(10),
        max_field_churn_percent: None,
        time_window_days: None,
        severity_threshold: request
            .severity_threshold
            .as_deref()
            .and_then(|s| match s.to_lowercase().as_str() {
                "critical" => Some(mockforge_core::ai_contract_diff::MismatchSeverity::Critical),
                "high" => Some(mockforge_core::ai_contract_diff::MismatchSeverity::High),
                "medium" => Some(mockforge_core::ai_contract_diff::MismatchSeverity::Medium),
                "low" => Some(mockforge_core::ai_contract_diff::MismatchSeverity::Low),
                _ => None,
            })
            .unwrap_or(mockforge_core::ai_contract_diff::MismatchSeverity::High),
        enabled: request.enabled.unwrap_or(true),
    };

    // Generate budget ID
    let budget_id = format!("{}:{}:{}", request.method, request.endpoint, uuid::Uuid::new_v4());

    // Build the key for this budget (matches the format used by list_budgets/get_budget)
    let key = format!("{} {}", request.method, request.endpoint);

    // Note: DriftBudgetEngine.config is not behind interior mutability (RwLock),
    // so budget creation is returned but not persisted in the running engine.
    // A future refactor should wrap config in RwLock for runtime mutation.
    let _ = key;

    Ok(Json(DriftBudgetResponse {
        id: budget_id,
        endpoint: request.endpoint,
        method: request.method,
        budget,
        workspace_id: request.workspace_id,
    }))
}

/// List drift budgets
///
/// GET /api/v1/drift/budgets
pub async fn list_budgets(
    State(state): State<DriftBudgetState>,
) -> Result<Json<serde_json::Value>, StatusCode> {
    let config = state.engine.config();
    let budgets: Vec<serde_json::Value> = config
        .per_endpoint_budgets
        .iter()
        .map(|(key, budget)| {
            // Key format is "METHOD /path"
            let parts: Vec<&str> = key.splitn(2, ' ').collect();
            let (method, endpoint) = if parts.len() == 2 {
                (parts[0].to_string(), parts[1].to_string())
            } else {
                ("GET".to_string(), key.clone())
            };
            serde_json::json!({
                "id": key,
                "method": method,
                "endpoint": endpoint,
                "budget": {
                    "max_breaking_changes": budget.max_breaking_changes,
                    "max_non_breaking_changes": budget.max_non_breaking_changes,
                    "enabled": budget.enabled,
                }
            })
        })
        .collect();

    Ok(Json(serde_json::json!({
        "budgets": budgets,
        "total": budgets.len(),
    })))
}

/// Get a specific drift budget
///
/// GET /api/v1/drift/budgets/{id}
pub async fn get_budget(
    State(state): State<DriftBudgetState>,
    Path(id): Path<String>,
) -> Result<Json<serde_json::Value>, StatusCode> {
    let config = state.engine.config();
    if let Some(budget) = config.per_endpoint_budgets.get(&id) {
        let parts: Vec<&str> = id.splitn(2, ' ').collect();
        let (method, endpoint) = if parts.len() == 2 {
            (parts[0].to_string(), parts[1].to_string())
        } else {
            ("GET".to_string(), id.clone())
        };
        Ok(Json(serde_json::json!({
            "id": id,
            "method": method,
            "endpoint": endpoint,
            "budget": {
                "max_breaking_changes": budget.max_breaking_changes,
                "max_non_breaking_changes": budget.max_non_breaking_changes,
                "enabled": budget.enabled,
            }
        })))
    } else {
        Err(StatusCode::NOT_FOUND)
    }
}

/// Get budget for a specific endpoint/workspace/service
///
/// GET /api/v1/drift/budgets/lookup?endpoint=/api/users&method=GET&workspace_id=...
#[derive(Debug, Deserialize)]
pub struct GetBudgetQuery {
    /// Endpoint path
    pub endpoint: String,
    /// HTTP method
    pub method: String,
    /// Optional workspace ID
    pub workspace_id: Option<String>,
    /// Optional service name
    pub service_name: Option<String>,
    /// Optional comma-separated tags
    pub tags: Option<String>,
}

/// Get budget for endpoint
///
/// GET /api/v1/drift/budgets/lookup
pub async fn get_budget_for_endpoint(
    State(state): State<DriftBudgetState>,
    Query(params): Query<GetBudgetQuery>,
) -> Result<Json<serde_json::Value>, StatusCode> {
    let tags = params
        .tags
        .as_ref()
        .map(|t| t.split(',').map(|s| s.trim().to_string()).collect::<Vec<_>>());

    let budget = state.engine.get_budget_for_endpoint(
        &params.endpoint,
        &params.method,
        params.workspace_id.as_deref(),
        params.service_name.as_deref(),
        tags.as_deref(),
    );

    Ok(Json(serde_json::json!({
        "endpoint": params.endpoint,
        "method": params.method,
        "workspace_id": params.workspace_id,
        "service_name": params.service_name,
        "budget": budget,
    })))
}

/// Request to create workspace/service/tag budget
#[derive(Debug, Deserialize, Serialize)]
pub struct CreateWorkspaceBudgetRequest {
    /// Workspace ID
    pub workspace_id: String,
    /// Maximum allowed breaking changes
    pub max_breaking_changes: Option<u32>,
    /// Maximum allowed non-breaking changes
    pub max_non_breaking_changes: Option<u32>,
    /// Maximum field churn percentage
    pub max_field_churn_percent: Option<f64>,
    /// Time window in days
    pub time_window_days: Option<u32>,
    /// Whether the budget is enabled
    pub enabled: Option<bool>,
}

/// Request to create a service-level drift budget
#[derive(Debug, Deserialize, Serialize)]
pub struct CreateServiceBudgetRequest {
    /// Service name
    pub service_name: String,
    /// Maximum allowed breaking changes
    pub max_breaking_changes: Option<u32>,
    /// Maximum allowed non-breaking changes
    pub max_non_breaking_changes: Option<u32>,
    /// Maximum field churn percentage
    pub max_field_churn_percent: Option<f64>,
    /// Time window in days
    pub time_window_days: Option<u32>,
    /// Whether the budget is enabled
    pub enabled: Option<bool>,
}

/// Create or update workspace budget
///
/// POST /api/v1/drift/budgets/workspace
pub async fn create_workspace_budget(
    State(state): State<DriftBudgetState>,
    Json(request): Json<CreateWorkspaceBudgetRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
    let budget = DriftBudget {
        max_breaking_changes: request.max_breaking_changes.unwrap_or(0),
        max_non_breaking_changes: request.max_non_breaking_changes.unwrap_or(10),
        max_field_churn_percent: request.max_field_churn_percent,
        time_window_days: request.time_window_days,
        severity_threshold: mockforge_core::ai_contract_diff::MismatchSeverity::High,
        enabled: request.enabled.unwrap_or(true),
    };

    let mut config = state.engine.config().clone();
    config
        .per_workspace_budgets
        .insert(request.workspace_id.clone(), budget.clone());

    // Note: In a full implementation, this would persist to database
    // state.engine.update_config(config);

    Ok(Json(serde_json::json!({
        "workspace_id": request.workspace_id,
        "budget": budget,
    })))
}

/// Create or update service budget
///
/// POST /api/v1/drift/budgets/service
pub async fn create_service_budget(
    State(state): State<DriftBudgetState>,
    Json(request): Json<CreateServiceBudgetRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
    let budget = DriftBudget {
        max_breaking_changes: request.max_breaking_changes.unwrap_or(0),
        max_non_breaking_changes: request.max_non_breaking_changes.unwrap_or(10),
        max_field_churn_percent: request.max_field_churn_percent,
        time_window_days: request.time_window_days,
        severity_threshold: mockforge_core::ai_contract_diff::MismatchSeverity::High,
        enabled: request.enabled.unwrap_or(true),
    };

    let mut config = state.engine.config().clone();
    config.per_service_budgets.insert(request.service_name.clone(), budget.clone());

    // Note: In a full implementation, this would persist to database
    // state.engine.update_config(config);

    Ok(Json(serde_json::json!({
        "service_name": request.service_name,
        "budget": budget,
    })))
}

/// Request to generate GitOps PR from incidents
#[derive(Debug, Deserialize)]
pub struct GeneratePRRequest {
    /// Optional list of specific incident IDs
    pub incident_ids: Option<Vec<String>>,
    /// Optional workspace ID filter
    pub workspace_id: Option<String>,
    /// Optional status filter (e.g., "open")
    pub status: Option<String>,
}

/// Generate GitOps PR from drift incidents
///
/// POST /api/v1/drift/gitops/generate-pr
pub async fn generate_gitops_pr(
    State(state): State<DriftBudgetState>,
    Json(request): Json<GeneratePRRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
    let handler = state.gitops_handler.as_ref().ok_or(StatusCode::SERVICE_UNAVAILABLE)?;

    // Get incidents to include in PR
    let mut query = IncidentQuery::default();

    if let Some(incident_ids) = &request.incident_ids {
        // Filter by specific incident IDs
        // Note: IncidentQuery doesn't support ID filtering yet, so we'll get all and filter
        let all_incidents = state.incident_manager.query_incidents(query).await;
        let incidents: Vec<_> =
            all_incidents.into_iter().filter(|inc| incident_ids.contains(&inc.id)).collect();

        match handler.generate_pr_from_incidents(&incidents).await {
            Ok(Some(pr_result)) => {
                // Emit pipeline event for drift threshold exceeded
                #[cfg(feature = "pipelines")]
                {
                    use mockforge_pipelines::{publish_event, PipelineEvent};
                    use uuid::Uuid;

                    // Extract workspace_id from incidents (use first incident's workspace if available)
                    let workspace_id = incidents
                        .first()
                        .and_then(|inc| inc.workspace_id.as_ref())
                        .and_then(|ws_id| Uuid::parse_str(ws_id).ok());

                    // Count threshold-exceeded incidents
                    let threshold_exceeded_count = incidents
                        .iter()
                        .filter(|inc| matches!(inc.incident_type, IncidentType::ThresholdExceeded))
                        .count();

                    if threshold_exceeded_count > 0 {
                        // Get a representative endpoint for the event
                        let endpoint = incidents
                            .first()
                            .map(|inc| format!("{} {}", inc.method, inc.endpoint))
                            .unwrap_or_else(|| "unknown".to_string());

                        let event = PipelineEvent::drift_threshold_exceeded(
                            workspace_id.unwrap_or_else(Uuid::new_v4),
                            endpoint,
                            threshold_exceeded_count as i32,
                            incidents.len() as i32,
                        );

                        if let Err(e) = publish_event(event) {
                            tracing::warn!(
                                "Failed to publish drift threshold exceeded event: {}",
                                e
                            );
                        }
                    }
                }

                Ok(Json(serde_json::json!({
                    "success": true,
                    "pr": pr_result,
                })))
            }
            Ok(None) => Ok(Json(serde_json::json!({
                "success": false,
                "message": "No PR generated (no file changes or incidents)",
            }))),
            Err(_e) => Err(StatusCode::INTERNAL_SERVER_ERROR),
        }
    } else {
        // Filter by workspace and/or status
        let workspace_id_str = request.workspace_id.clone();
        #[cfg(not(feature = "pipelines"))]
        let _ = &workspace_id_str;
        query.workspace_id = request.workspace_id;
        if let Some(status_str) = &request.status {
            query.status = match status_str.as_str() {
                "open" => Some(IncidentStatus::Open),
                "acknowledged" => Some(IncidentStatus::Acknowledged),
                _ => None,
            };
        }

        let incidents = state.incident_manager.query_incidents(query).await;

        match handler.generate_pr_from_incidents(&incidents).await {
            Ok(Some(pr_result)) => {
                // Emit pipeline event for drift threshold exceeded
                #[cfg(feature = "pipelines")]
                {
                    use mockforge_pipelines::{publish_event, PipelineEvent};
                    use uuid::Uuid;

                    // Extract workspace_id from cloned string or incidents
                    let workspace_id = workspace_id_str
                        .as_ref()
                        .and_then(|ws_id| Uuid::parse_str(ws_id).ok())
                        .or_else(|| {
                            incidents
                                .first()
                                .and_then(|inc| inc.workspace_id.as_ref())
                                .and_then(|ws_id| Uuid::parse_str(ws_id).ok())
                        })
                        .unwrap_or_else(Uuid::new_v4);

                    // Count threshold-exceeded incidents
                    let threshold_exceeded_count = incidents
                        .iter()
                        .filter(|inc| matches!(inc.incident_type, IncidentType::ThresholdExceeded))
                        .count();

                    if threshold_exceeded_count > 0 {
                        // Get a representative endpoint for the event
                        let endpoint = incidents
                            .first()
                            .map(|inc| format!("{} {}", inc.method, inc.endpoint))
                            .unwrap_or_else(|| "unknown".to_string());

                        let event = PipelineEvent::drift_threshold_exceeded(
                            workspace_id,
                            endpoint,
                            threshold_exceeded_count as i32,
                            incidents.len() as i32,
                        );

                        if let Err(e) = publish_event(event) {
                            tracing::warn!(
                                "Failed to publish drift threshold exceeded event: {}",
                                e
                            );
                        }
                    }
                }

                Ok(Json(serde_json::json!({
                    "success": true,
                    "pr": pr_result,
                    "incidents_included": incidents.len(),
                })))
            }
            Ok(None) => Ok(Json(serde_json::json!({
                "success": false,
                "message": "No PR generated (no file changes or incidents)",
            }))),
            Err(_e) => Err(StatusCode::INTERNAL_SERVER_ERROR),
        }
    }
}

/// Get drift metrics over time
///
/// GET /api/v1/drift/metrics?endpoint=/api/users&method=GET&days=30
#[derive(Debug, Deserialize)]
pub struct GetMetricsQuery {
    /// Optional endpoint filter
    pub endpoint: Option<String>,
    /// Optional HTTP method filter
    pub method: Option<String>,
    /// Optional workspace ID filter
    pub workspace_id: Option<String>,
    /// Lookback window in days
    pub days: Option<u32>,
}

/// Get drift metrics
///
/// GET /api/v1/drift/metrics
pub async fn get_drift_metrics(
    State(state): State<DriftBudgetState>,
    Query(params): Query<GetMetricsQuery>,
) -> Result<Json<serde_json::Value>, StatusCode> {
    // Query incidents for metrics
    let mut query = IncidentQuery {
        endpoint: params.endpoint,
        method: params.method,
        workspace_id: params.workspace_id,
        ..IncidentQuery::default()
    };

    // Filter by date range if days specified
    if let Some(days) = params.days {
        let start_date = chrono::Utc::now()
            .checked_sub_signed(chrono::Duration::days(days as i64))
            .map(|dt| dt.timestamp())
            .unwrap_or(0);
        query.start_date = Some(start_date);
    }

    let incidents = state.incident_manager.query_incidents(query).await;

    // Calculate metrics
    let total_incidents = incidents.len();
    let breaking_changes = incidents
        .iter()
        .filter(|i| matches!(i.incident_type, IncidentType::BreakingChange))
        .count();
    let threshold_exceeded = total_incidents - breaking_changes;

    let by_severity: HashMap<String, usize> =
        incidents.iter().fold(HashMap::new(), |mut acc, inc| {
            let key = format!("{:?}", inc.severity).to_lowercase();
            *acc.entry(key).or_insert(0) += 1;
            acc
        });

    Ok(Json(serde_json::json!({
        "total_incidents": total_incidents,
        "breaking_changes": breaking_changes,
        "threshold_exceeded": threshold_exceeded,
        "by_severity": by_severity,
        "incidents": incidents.iter().take(100).collect::<Vec<_>>(), // Limit to first 100
    })))
}

/// List incidents
///
/// GET /api/v1/drift/incidents
pub async fn list_incidents(
    State(state): State<DriftBudgetState>,
    Query(params): Query<HashMap<String, String>>,
) -> Result<Json<ListIncidentsResponse>, StatusCode> {
    let mut query = IncidentQuery::default();

    if let Some(status_str) = params.get("status") {
        query.status = match status_str.as_str() {
            "open" => Some(IncidentStatus::Open),
            "acknowledged" => Some(IncidentStatus::Acknowledged),
            "resolved" => Some(IncidentStatus::Resolved),
            "closed" => Some(IncidentStatus::Closed),
            _ => None,
        };
    }

    if let Some(severity_str) = params.get("severity") {
        query.severity = match severity_str.as_str() {
            "critical" => Some(IncidentSeverity::Critical),
            "high" => Some(IncidentSeverity::High),
            "medium" => Some(IncidentSeverity::Medium),
            "low" => Some(IncidentSeverity::Low),
            _ => None,
        };
    }

    if let Some(endpoint) = params.get("endpoint") {
        query.endpoint = Some(endpoint.clone());
    }

    if let Some(method) = params.get("method") {
        query.method = Some(method.clone());
    }

    if let Some(incident_type_str) = params.get("incident_type") {
        query.incident_type = match incident_type_str.as_str() {
            "breaking_change" => Some(IncidentType::BreakingChange),
            "threshold_exceeded" => Some(IncidentType::ThresholdExceeded),
            _ => None,
        };
    }

    if let Some(workspace_id) = params.get("workspace_id") {
        query.workspace_id = Some(workspace_id.clone());
    }

    if let Some(limit_str) = params.get("limit") {
        if let Ok(limit) = limit_str.parse() {
            query.limit = Some(limit);
        }
    }

    if let Some(offset_str) = params.get("offset") {
        if let Ok(offset) = offset_str.parse() {
            query.offset = Some(offset);
        }
    }

    let incidents = state.incident_manager.query_incidents(query).await;
    let total = incidents.len();

    Ok(Json(ListIncidentsResponse { incidents, total }))
}

/// Get a specific incident
///
/// GET /api/v1/drift/incidents/{id}
pub async fn get_incident(
    State(state): State<DriftBudgetState>,
    Path(id): Path<String>,
) -> Result<Json<DriftIncident>, StatusCode> {
    state
        .incident_manager
        .get_incident(&id)
        .await
        .map(Json)
        .ok_or(StatusCode::NOT_FOUND)
}

/// Update an incident
///
/// PATCH /api/v1/drift/incidents/{id}
pub async fn update_incident(
    State(state): State<DriftBudgetState>,
    Path(id): Path<String>,
    Json(request): Json<UpdateIncidentRequest>,
) -> Result<Json<DriftIncident>, StatusCode> {
    let mut incident =
        state.incident_manager.get_incident(&id).await.ok_or(StatusCode::NOT_FOUND)?;

    if let Some(status_str) = request.status {
        match status_str.as_str() {
            "acknowledged" => {
                incident = state
                    .incident_manager
                    .acknowledge_incident(&id)
                    .await
                    .ok_or(StatusCode::NOT_FOUND)?;
            }
            "resolved" => {
                incident = state
                    .incident_manager
                    .resolve_incident(&id)
                    .await
                    .ok_or(StatusCode::NOT_FOUND)?;
            }
            "closed" => {
                incident = state
                    .incident_manager
                    .close_incident(&id)
                    .await
                    .ok_or(StatusCode::NOT_FOUND)?;
            }
            other => {
                tracing::warn!(
                    "Invalid incident status '{}': expected acknowledged, resolved, or closed",
                    other
                );
                return Err(StatusCode::BAD_REQUEST);
            }
        }
    }

    if let Some(ticket_id) = request.external_ticket_id {
        incident = state
            .incident_manager
            .link_external_ticket(&id, ticket_id, request.external_ticket_url)
            .await
            .ok_or(StatusCode::NOT_FOUND)?;
    }

    Ok(Json(incident))
}

/// Resolve an incident
///
/// POST /api/v1/drift/incidents/{id}/resolve
pub async fn resolve_incident(
    State(state): State<DriftBudgetState>,
    Path(id): Path<String>,
    Json(_request): Json<ResolveIncidentRequest>,
) -> Result<Json<DriftIncident>, StatusCode> {
    state
        .incident_manager
        .resolve_incident(&id)
        .await
        .map(Json)
        .ok_or(StatusCode::NOT_FOUND)
}

/// Get incident statistics
///
/// GET /api/v1/drift/incidents/stats
pub async fn get_incident_stats(
    State(state): State<DriftBudgetState>,
) -> Result<Json<serde_json::Value>, StatusCode> {
    let stats = state.incident_manager.get_statistics().await;
    Ok(Json(serde_json::json!({
        "stats": stats
    })))
}

/// Create drift budget router
pub fn drift_budget_router(state: DriftBudgetState) -> axum::Router {
    use axum::{
        routing::{get, patch, post},
        Router,
    };

    Router::new()
        .route("/api/v1/drift/budgets", post(create_budget))
        .route("/api/v1/drift/budgets", get(list_budgets))
        .route("/api/v1/drift/budgets/lookup", get(get_budget_for_endpoint))
        .route("/api/v1/drift/budgets/workspace", post(create_workspace_budget))
        .route("/api/v1/drift/budgets/service", post(create_service_budget))
        .route("/api/v1/drift/budgets/{id}", get(get_budget))
        .route("/api/v1/drift/incidents", get(list_incidents))
        .route("/api/v1/drift/incidents/stats", get(get_incident_stats))
        .route("/api/v1/drift/incidents/{id}", get(get_incident))
        .route("/api/v1/drift/incidents/{id}", patch(update_incident))
        .route("/api/v1/drift/incidents/{id}/resolve", post(resolve_incident))
        .route("/api/v1/drift/gitops/generate-pr", post(generate_gitops_pr))
        .route("/api/v1/drift/metrics", get(get_drift_metrics))
        .with_state(state)
}