mockforge-ui 0.3.135

Admin UI for MockForge - web-based interface for managing mock servers
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
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
//! Admin API handlers for time travel features

use axum::{
    extract::Path,
    http::StatusCode,
    response::{IntoResponse, Json},
};
use chrono::{DateTime, Duration, Utc};
use mockforge_core::{
    time_travel::cron::{CronJob, CronJobAction},
    RepeatConfig, ScheduledResponse, TimeScenario, TimeTravelManager, VirtualClock,
};
use mockforge_vbr::{MutationOperation, MutationRule, MutationRuleManager, MutationTrigger};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use tracing::info;

/// Global time travel manager (optional, can be set by the application)
static TIME_TRAVEL_MANAGER: once_cell::sync::OnceCell<Arc<RwLock<Option<Arc<TimeTravelManager>>>>> =
    once_cell::sync::OnceCell::new();
static SCENARIO_STORE: once_cell::sync::Lazy<Arc<RwLock<HashMap<String, TimeScenario>>>> =
    once_cell::sync::Lazy::new(|| Arc::new(RwLock::new(HashMap::new())));

/// Initialize the global time travel manager
pub fn init_time_travel_manager(manager: Arc<TimeTravelManager>) {
    let cell = TIME_TRAVEL_MANAGER.get_or_init(|| Arc::new(RwLock::new(None)));
    let mut guard = cell.write().unwrap();
    *guard = Some(manager);
}

/// Get the global time travel manager
fn get_time_travel_manager() -> Option<Arc<TimeTravelManager>> {
    TIME_TRAVEL_MANAGER.get().and_then(|cell| cell.read().unwrap().clone())
}

fn save_scenario_to_store(scenario: TimeScenario) {
    let mut store = SCENARIO_STORE.write().unwrap();
    store.insert(scenario.name.clone(), scenario);
}

fn load_scenario_from_store(name: &str) -> Option<TimeScenario> {
    let store = SCENARIO_STORE.read().unwrap();
    store.get(name).cloned()
}

/// Global mutation rule manager (optional, can be set by the application)
static MUTATION_RULE_MANAGER: once_cell::sync::OnceCell<
    Arc<RwLock<Option<Arc<MutationRuleManager>>>>,
> = once_cell::sync::OnceCell::new();

/// Initialize the global mutation rule manager
pub fn init_mutation_rule_manager(manager: Arc<MutationRuleManager>) {
    let cell = MUTATION_RULE_MANAGER.get_or_init(|| Arc::new(RwLock::new(None)));
    let mut guard = cell.write().unwrap();
    *guard = Some(manager);
}

/// Get the global mutation rule manager
fn get_mutation_rule_manager() -> Option<Arc<MutationRuleManager>> {
    MUTATION_RULE_MANAGER.get().and_then(|cell| cell.read().unwrap().clone())
}

/// Request to enable time travel at a specific time
#[derive(Debug, Serialize, Deserialize)]
pub struct EnableTimeTravelRequest {
    /// The time to set (ISO 8601 format)
    pub time: Option<DateTime<Utc>>,
    /// Time scale factor (default: 1.0)
    pub scale: Option<f64>,
}

/// Request to advance time
#[derive(Debug, Serialize, Deserialize)]
pub struct AdvanceTimeRequest {
    /// Duration to advance (e.g., "2h", "30m", "10s")
    pub duration: String,
}

/// Request to set time scale
#[derive(Debug, Serialize, Deserialize)]
pub struct SetScaleRequest {
    /// Time scale factor (1.0 = real time, 2.0 = 2x speed)
    pub scale: f64,
}

/// Request to schedule a response
#[derive(Debug, Serialize, Deserialize)]
pub struct ScheduleResponseRequest {
    /// When to trigger (ISO 8601 format or relative like "+1h")
    pub trigger_time: String,
    /// Response body (JSON)
    pub body: serde_json::Value,
    /// HTTP status code (default: 200)
    #[serde(default = "default_status")]
    pub status: u16,
    /// Response headers
    #[serde(default)]
    pub headers: HashMap<String, String>,
    /// Optional name/label
    pub name: Option<String>,
    /// Repeat configuration
    pub repeat: Option<RepeatConfig>,
}

fn default_status() -> u16 {
    200
}

/// Response with scheduled response ID
#[derive(Debug, Serialize, Deserialize)]
pub struct ScheduleResponseResponse {
    pub id: String,
    pub trigger_time: DateTime<Utc>,
}

/// Get time travel status
pub async fn get_time_travel_status() -> impl IntoResponse {
    match get_time_travel_manager() {
        Some(manager) => {
            let status = manager.clock().status();
            Json(status).into_response()
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Time travel not initialized"
            })),
        )
            .into_response(),
    }
}

/// Enable time travel
pub async fn enable_time_travel(Json(req): Json<EnableTimeTravelRequest>) -> impl IntoResponse {
    match get_time_travel_manager() {
        Some(manager) => {
            let time = req.time.unwrap_or_else(Utc::now);
            manager.enable_and_set(time);

            if let Some(scale) = req.scale {
                manager.set_scale(scale);
            }

            info!("Time travel enabled at {}", time);

            Json(serde_json::json!({
                "success": true,
                "status": manager.clock().status()
            }))
            .into_response()
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Time travel not initialized"
            })),
        )
            .into_response(),
    }
}

/// Disable time travel
pub async fn disable_time_travel() -> impl IntoResponse {
    match get_time_travel_manager() {
        Some(manager) => {
            manager.disable();
            info!("Time travel disabled");

            Json(serde_json::json!({
                "success": true,
                "status": manager.clock().status()
            }))
            .into_response()
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Time travel not initialized"
            })),
        )
            .into_response(),
    }
}

/// Advance time by a duration
pub async fn advance_time(Json(req): Json<AdvanceTimeRequest>) -> impl IntoResponse {
    match get_time_travel_manager() {
        Some(manager) => {
            // Parse duration string (e.g., "2h", "30m", "10s", "1week")
            let duration = parse_duration(&req.duration);

            match duration {
                Ok(dur) => {
                    manager.advance(dur);
                    info!("Time advanced by {}", req.duration);

                    Json(serde_json::json!({
                        "success": true,
                        "status": manager.clock().status()
                    }))
                    .into_response()
                }
                Err(e) => (
                    StatusCode::BAD_REQUEST,
                    Json(serde_json::json!({
                        "error": format!("Invalid duration format: {}", e)
                    })),
                )
                    .into_response(),
            }
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Time travel not initialized"
            })),
        )
            .into_response(),
    }
}

/// Set time scale
pub async fn set_time_scale(Json(req): Json<SetScaleRequest>) -> impl IntoResponse {
    match get_time_travel_manager() {
        Some(manager) => {
            manager.set_scale(req.scale);
            info!("Time scale set to {}x", req.scale);

            Json(serde_json::json!({
                "success": true,
                "status": manager.clock().status()
            }))
            .into_response()
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Time travel not initialized"
            })),
        )
            .into_response(),
    }
}

/// Request to set virtual time
#[derive(Debug, Serialize, Deserialize)]
pub struct SetTimeRequest {
    /// The time to set (ISO 8601 format)
    pub time: DateTime<Utc>,
}

/// Set virtual time to a specific point
pub async fn set_time(Json(req): Json<SetTimeRequest>) -> impl IntoResponse {
    match get_time_travel_manager() {
        Some(manager) => {
            manager.clock().set_time(req.time);
            info!("Virtual time set to {}", req.time);

            Json(serde_json::json!({
                "success": true,
                "status": manager.clock().status()
            }))
            .into_response()
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Time travel not initialized"
            })),
        )
            .into_response(),
    }
}

/// Reset time travel
pub async fn reset_time_travel() -> impl IntoResponse {
    match get_time_travel_manager() {
        Some(manager) => {
            manager.clock().reset();
            info!("Time travel reset");

            Json(serde_json::json!({
                "success": true,
                "status": manager.clock().status()
            }))
            .into_response()
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Time travel not initialized"
            })),
        )
            .into_response(),
    }
}

/// Schedule a response
pub async fn schedule_response(Json(req): Json<ScheduleResponseRequest>) -> impl IntoResponse {
    match get_time_travel_manager() {
        Some(manager) => {
            // Parse trigger time (ISO 8601 or relative like "+1h")
            let trigger_time = parse_trigger_time(&req.trigger_time, manager.clock());

            match trigger_time {
                Ok(time) => {
                    let scheduled_response = ScheduledResponse {
                        id: uuid::Uuid::new_v4().to_string(),
                        trigger_time: time,
                        body: req.body,
                        status: req.status,
                        headers: req.headers,
                        name: req.name,
                        repeat: req.repeat,
                    };

                    match manager.scheduler().schedule(scheduled_response.clone()) {
                        Ok(id) => {
                            info!("Scheduled response {} for {}", id, time);

                            Json(ScheduleResponseResponse {
                                id,
                                trigger_time: time,
                            })
                            .into_response()
                        }
                        Err(e) => (
                            StatusCode::INTERNAL_SERVER_ERROR,
                            Json(serde_json::json!({
                                "error": format!("Failed to schedule response: {}", e)
                            })),
                        )
                            .into_response(),
                    }
                }
                Err(e) => (
                    StatusCode::BAD_REQUEST,
                    Json(serde_json::json!({
                        "error": format!("Invalid trigger time: {}", e)
                    })),
                )
                    .into_response(),
            }
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Time travel not initialized"
            })),
        )
            .into_response(),
    }
}

/// List scheduled responses
pub async fn list_scheduled_responses() -> impl IntoResponse {
    match get_time_travel_manager() {
        Some(manager) => {
            let scheduled = manager.scheduler().list_scheduled();
            Json(scheduled).into_response()
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Time travel not initialized"
            })),
        )
            .into_response(),
    }
}

/// Cancel a scheduled response
pub async fn cancel_scheduled_response(Path(id): Path<String>) -> impl IntoResponse {
    match get_time_travel_manager() {
        Some(manager) => {
            let cancelled = manager.scheduler().cancel(&id);

            if cancelled {
                info!("Cancelled scheduled response {}", id);
                Json(serde_json::json!({
                    "success": true
                }))
                .into_response()
            } else {
                (
                    StatusCode::NOT_FOUND,
                    Json(serde_json::json!({
                        "error": "Scheduled response not found"
                    })),
                )
                    .into_response()
            }
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Time travel not initialized"
            })),
        )
            .into_response(),
    }
}

/// Clear all scheduled responses
pub async fn clear_scheduled_responses() -> impl IntoResponse {
    match get_time_travel_manager() {
        Some(manager) => {
            manager.scheduler().clear_all();
            info!("Cleared all scheduled responses");

            Json(serde_json::json!({
                "success": true
            }))
            .into_response()
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Time travel not initialized"
            })),
        )
            .into_response(),
    }
}

/// Request to save a scenario
#[derive(Debug, Serialize, Deserialize)]
pub struct SaveScenarioRequest {
    /// Scenario name
    pub name: String,
    /// Optional description
    pub description: Option<String>,
}

/// Request to load a scenario
#[derive(Debug, Serialize, Deserialize)]
pub struct LoadScenarioRequest {
    /// Scenario name
    pub name: String,
}

/// Save current time travel state as a scenario
pub async fn save_scenario(Json(req): Json<SaveScenarioRequest>) -> impl IntoResponse {
    match get_time_travel_manager() {
        Some(manager) => {
            let mut scenario = manager.save_scenario(req.name.clone());
            scenario.description = req.description;
            save_scenario_to_store(scenario.clone());

            Json(scenario).into_response()
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Time travel not initialized"
            })),
        )
            .into_response(),
    }
}

/// Load a scenario from the in-memory scenario store and apply it.
pub async fn load_scenario(Json(req): Json<LoadScenarioRequest>) -> impl IntoResponse {
    match get_time_travel_manager() {
        Some(manager) => {
            if let Some(scenario) = load_scenario_from_store(&req.name) {
                manager.load_scenario(&scenario);
                Json(serde_json::json!({
                    "success": true,
                    "scenario": scenario,
                }))
                .into_response()
            } else {
                (
                    StatusCode::NOT_FOUND,
                    Json(serde_json::json!({
                        "error": format!("Scenario '{}' not found", req.name)
                    })),
                )
                    .into_response()
            }
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Time travel not initialized"
            })),
        )
            .into_response(),
    }
}

/// Request to create a cron job
#[derive(Debug, Serialize, Deserialize)]
pub struct CreateCronJobRequest {
    /// Job ID
    pub id: String,
    /// Job name
    pub name: String,
    /// Cron schedule (e.g., "0 3 * * *")
    pub schedule: String,
    /// Optional description
    #[serde(default)]
    pub description: Option<String>,
    /// Action type: "callback", "response", or "mutation"
    pub action_type: String,
    /// Action metadata (JSON)
    #[serde(default)]
    pub action_metadata: serde_json::Value,
}

/// List all cron jobs
pub async fn list_cron_jobs() -> impl IntoResponse {
    match get_time_travel_manager() {
        Some(manager) => {
            let jobs = manager.cron_scheduler().list_jobs().await;
            Json(serde_json::json!({
                "success": true,
                "jobs": jobs
            }))
            .into_response()
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Time travel not initialized"
            })),
        )
            .into_response(),
    }
}

/// Get a specific cron job
pub async fn get_cron_job(Path(id): Path<String>) -> impl IntoResponse {
    match get_time_travel_manager() {
        Some(manager) => match manager.cron_scheduler().get_job(&id).await {
            Some(job) => Json(serde_json::json!({
                "success": true,
                "job": job
            }))
            .into_response(),
            None => (
                StatusCode::NOT_FOUND,
                Json(serde_json::json!({
                    "error": format!("Cron job '{}' not found", id)
                })),
            )
                .into_response(),
        },
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Time travel not initialized"
            })),
        )
            .into_response(),
    }
}

/// Create a new cron job
pub async fn create_cron_job(Json(req): Json<CreateCronJobRequest>) -> impl IntoResponse {
    match get_time_travel_manager() {
        Some(manager) => {
            // Create the job
            let mut job = CronJob::new(req.id.clone(), req.name.clone(), req.schedule.clone());
            if let Some(desc) = req.description {
                job.description = Some(desc);
            }

            // Create the action based on type
            let action = match req.action_type.as_str() {
                "callback" => {
                    let job_id = req.id.clone();
                    CronJobAction::Callback(Box::new(move |_| {
                        info!("Cron job '{}' executed (callback)", job_id);
                        Ok(())
                    }))
                }
                "response" => {
                    let body =
                        req.action_metadata.get("body").cloned().unwrap_or(serde_json::json!({}));
                    let status = req
                        .action_metadata
                        .get("status")
                        .and_then(|v| v.as_u64())
                        .map(|v| v as u16)
                        .unwrap_or(200);
                    let headers = req
                        .action_metadata
                        .get("headers")
                        .and_then(|v| v.as_object())
                        .map(|obj| {
                            obj.iter()
                                .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
                                .collect()
                        })
                        .unwrap_or_default();

                    CronJobAction::ScheduledResponse {
                        body,
                        status,
                        headers,
                    }
                }
                "mutation" => {
                    let entity = req
                        .action_metadata
                        .get("entity")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string())
                        .unwrap_or_default();
                    let operation = req
                        .action_metadata
                        .get("operation")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string())
                        .unwrap_or_default();

                    CronJobAction::DataMutation { entity, operation }
                }
                _ => {
                    return (
                        StatusCode::BAD_REQUEST,
                        Json(serde_json::json!({
                            "error": format!("Invalid action type: {}", req.action_type)
                        })),
                    )
                        .into_response();
                }
            };

            match manager.cron_scheduler().add_job(job, action).await {
                Ok(_) => {
                    info!("Created cron job '{}'", req.id);
                    Json(serde_json::json!({
                        "success": true,
                        "message": format!("Cron job '{}' created", req.id)
                    }))
                    .into_response()
                }
                Err(e) => (
                    StatusCode::BAD_REQUEST,
                    Json(serde_json::json!({
                        "error": e.to_string()
                    })),
                )
                    .into_response(),
            }
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Time travel not initialized"
            })),
        )
            .into_response(),
    }
}

/// Delete a cron job
pub async fn delete_cron_job(Path(id): Path<String>) -> impl IntoResponse {
    match get_time_travel_manager() {
        Some(manager) => {
            let removed = manager.cron_scheduler().remove_job(&id).await;
            if removed {
                info!("Deleted cron job '{}'", id);
                Json(serde_json::json!({
                    "success": true,
                    "message": format!("Cron job '{}' deleted", id)
                }))
                .into_response()
            } else {
                (
                    StatusCode::NOT_FOUND,
                    Json(serde_json::json!({
                        "error": format!("Cron job '{}' not found", id)
                    })),
                )
                    .into_response()
            }
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Time travel not initialized"
            })),
        )
            .into_response(),
    }
}

/// Enable or disable a cron job
#[derive(Debug, Serialize, Deserialize)]
pub struct SetCronJobEnabledRequest {
    /// Whether to enable the job
    pub enabled: bool,
}

pub async fn set_cron_job_enabled(
    Path(id): Path<String>,
    Json(req): Json<SetCronJobEnabledRequest>,
) -> impl IntoResponse {
    match get_time_travel_manager() {
        Some(manager) => match manager.cron_scheduler().set_job_enabled(&id, req.enabled).await {
            Ok(_) => {
                info!("Cron job '{}' {}", id, if req.enabled { "enabled" } else { "disabled" });
                Json(serde_json::json!({
                        "success": true,
                        "message": format!("Cron job '{}' {}", id, if req.enabled { "enabled" } else { "disabled" })
                    }))
                    .into_response()
            }
            Err(e) => (
                StatusCode::NOT_FOUND,
                Json(serde_json::json!({
                    "error": e.to_string()
                })),
            )
                .into_response(),
        },
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Time travel not initialized"
            })),
        )
            .into_response(),
    }
}

/// Request to create a mutation rule
#[derive(Debug, Serialize, Deserialize)]
pub struct CreateMutationRuleRequest {
    /// Rule ID
    pub id: String,
    /// Entity name
    pub entity_name: String,
    /// Trigger configuration
    pub trigger: MutationTrigger,
    /// Operation configuration
    pub operation: MutationOperation,
    /// Optional description
    #[serde(default)]
    pub description: Option<String>,
    /// Optional condition (JSONPath)
    #[serde(default)]
    pub condition: Option<String>,
}

/// List all mutation rules
pub async fn list_mutation_rules() -> impl IntoResponse {
    match get_mutation_rule_manager() {
        Some(manager) => {
            let rules = manager.list_rules().await;
            Json(serde_json::json!({
                "success": true,
                "rules": rules
            }))
            .into_response()
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Mutation rule manager not initialized"
            })),
        )
            .into_response(),
    }
}

/// Get a specific mutation rule
pub async fn get_mutation_rule(Path(id): Path<String>) -> impl IntoResponse {
    match get_mutation_rule_manager() {
        Some(manager) => match manager.get_rule(&id).await {
            Some(rule) => Json(serde_json::json!({
                "success": true,
                "rule": rule
            }))
            .into_response(),
            None => (
                StatusCode::NOT_FOUND,
                Json(serde_json::json!({
                    "error": format!("Mutation rule '{}' not found", id)
                })),
            )
                .into_response(),
        },
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Mutation rule manager not initialized"
            })),
        )
            .into_response(),
    }
}

/// Create a new mutation rule
pub async fn create_mutation_rule(Json(req): Json<CreateMutationRuleRequest>) -> impl IntoResponse {
    match get_mutation_rule_manager() {
        Some(manager) => {
            let mut rule = MutationRule::new(
                req.id.clone(),
                req.entity_name.clone(),
                req.trigger.clone(),
                req.operation.clone(),
            );
            if let Some(desc) = req.description {
                rule.description = Some(desc);
            }
            if let Some(cond) = req.condition {
                rule.condition = Some(cond);
            }

            match manager.add_rule(rule).await {
                Ok(_) => {
                    info!("Created mutation rule '{}'", req.id);
                    Json(serde_json::json!({
                        "success": true,
                        "message": format!("Mutation rule '{}' created", req.id)
                    }))
                    .into_response()
                }
                Err(e) => (
                    StatusCode::BAD_REQUEST,
                    Json(serde_json::json!({
                        "error": e.to_string().to_string()
                    })),
                )
                    .into_response(),
            }
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Mutation rule manager not initialized"
            })),
        )
            .into_response(),
    }
}

/// Delete a mutation rule
pub async fn delete_mutation_rule(Path(id): Path<String>) -> impl IntoResponse {
    match get_mutation_rule_manager() {
        Some(manager) => {
            let removed = manager.remove_rule(&id).await;
            if removed {
                info!("Deleted mutation rule '{}'", id);
                Json(serde_json::json!({
                    "success": true,
                    "message": format!("Mutation rule '{}' deleted", id)
                }))
                .into_response()
            } else {
                (
                    StatusCode::NOT_FOUND,
                    Json(serde_json::json!({
                        "error": format!("Mutation rule '{}' not found", id)
                    })),
                )
                    .into_response()
            }
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Mutation rule manager not initialized"
            })),
        )
            .into_response(),
    }
}

/// Enable or disable a mutation rule
#[derive(Debug, Serialize, Deserialize)]
pub struct SetMutationRuleEnabledRequest {
    /// Whether to enable the rule
    pub enabled: bool,
}

pub async fn set_mutation_rule_enabled(
    Path(id): Path<String>,
    Json(req): Json<SetMutationRuleEnabledRequest>,
) -> impl IntoResponse {
    match get_mutation_rule_manager() {
        Some(manager) => match manager.set_rule_enabled(&id, req.enabled).await {
            Ok(_) => {
                info!(
                    "Mutation rule '{}' {}",
                    id,
                    if req.enabled { "enabled" } else { "disabled" }
                );
                Json(serde_json::json!({
                        "success": true,
                        "message": format!("Mutation rule '{}' {}", id, if req.enabled { "enabled" } else { "disabled" })
                    }))
                    .into_response()
            }
            Err(e) => (
                StatusCode::NOT_FOUND,
                Json(serde_json::json!({
                    "error": e.to_string()
                })),
            )
                .into_response(),
        },
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Mutation rule manager not initialized"
            })),
        )
            .into_response(),
    }
}

/// Parse a duration string like "2h", "30m", "10s", "1d", "+1h", "+1 week", "1month", "1year"
///
/// Supports:
/// - Standard formats: "1h", "30m", "2d", etc.
/// - With + prefix: "+1h", "+1 week", "+2d"
/// - Week units: "1week", "1 week", "2weeks", "+1week"
/// - Month/year: "1month", "1year"
fn parse_duration(s: &str) -> Result<Duration, String> {
    let s = s.trim();
    if s.is_empty() {
        return Err("Empty duration string".to_string());
    }

    // Strip leading + or - (for relative time notation)
    let s = s.strip_prefix('+').unwrap_or(s);
    let s = s.strip_prefix('-').unwrap_or(s);

    // Handle weeks (with or without space)
    if s.ends_with("week") || s.ends_with("weeks") || s.ends_with(" week") || s.ends_with(" weeks")
    {
        let num_str = s
            .trim_end_matches("week")
            .trim_end_matches("weeks")
            .trim_end_matches(" week")
            .trim_end_matches(" weeks")
            .trim();
        let amount: i64 =
            num_str.parse().map_err(|e| format!("Invalid number for weeks: {}", e))?;
        // 1 week = 7 days
        return Ok(Duration::days(amount * 7));
    }

    // Handle months and years (approximate)
    if s.ends_with("month")
        || s.ends_with("months")
        || s.ends_with(" month")
        || s.ends_with(" months")
    {
        let num_str = s
            .trim_end_matches("month")
            .trim_end_matches("months")
            .trim_end_matches(" month")
            .trim_end_matches(" months")
            .trim();
        let amount: i64 =
            num_str.parse().map_err(|e| format!("Invalid number for months: {}", e))?;
        // Approximate: 1 month = 30 days
        return Ok(Duration::days(amount * 30));
    }
    if s.ends_with('y')
        || s.ends_with("year")
        || s.ends_with("years")
        || s.ends_with(" year")
        || s.ends_with(" years")
    {
        let num_str = s
            .trim_end_matches('y')
            .trim_end_matches("year")
            .trim_end_matches("years")
            .trim_end_matches(" year")
            .trim_end_matches(" years")
            .trim();
        let amount: i64 =
            num_str.parse().map_err(|e| format!("Invalid number for years: {}", e))?;
        // Approximate: 1 year = 365 days
        return Ok(Duration::days(amount * 365));
    }

    // Extract number and unit for standard durations
    let (num_str, unit) = if let Some(pos) = s.chars().position(|c| !c.is_numeric() && c != '-') {
        (&s[..pos], &s[pos..].trim())
    } else {
        return Err("No unit specified (use s, m, h, d, week, month, or year)".to_string());
    };

    let amount: i64 = num_str.parse().map_err(|e| format!("Invalid number: {}", e))?;

    match *unit {
        "s" | "sec" | "secs" | "second" | "seconds" => Ok(Duration::seconds(amount)),
        "m" | "min" | "mins" | "minute" | "minutes" => Ok(Duration::minutes(amount)),
        "h" | "hr" | "hrs" | "hour" | "hours" => Ok(Duration::hours(amount)),
        "d" | "day" | "days" => Ok(Duration::days(amount)),
        "w" | "week" | "weeks" => Ok(Duration::days(amount * 7)),
        _ => Err(format!("Unknown unit: {}. Use s, m, h, d, week, month, or year", unit)),
    }
}

/// Parse a trigger time (ISO 8601 or relative like "+1h")
fn parse_trigger_time(s: &str, clock: Arc<VirtualClock>) -> Result<DateTime<Utc>, String> {
    let s = s.trim();

    // Check if it's a relative time (starts with + or -)
    if s.starts_with('+') || s.starts_with('-') {
        let duration = parse_duration(&s[1..])?;
        let current = clock.now();

        if s.starts_with('+') {
            Ok(current + duration)
        } else {
            Ok(current - duration)
        }
    } else {
        // Parse as ISO 8601
        DateTime::parse_from_rfc3339(s)
            .map(|dt| dt.with_timezone(&Utc))
            .map_err(|e| format!("Invalid ISO 8601 date: {}", e))
    }
}

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

    #[test]
    fn test_parse_duration() {
        assert_eq!(parse_duration("10s").unwrap(), Duration::seconds(10));
        assert_eq!(parse_duration("30m").unwrap(), Duration::minutes(30));
        assert_eq!(parse_duration("2h").unwrap(), Duration::hours(2));
        assert_eq!(parse_duration("1d").unwrap(), Duration::days(1));

        assert!(parse_duration("").is_err());
        assert!(parse_duration("10").is_err());
        assert!(parse_duration("10x").is_err());
    }

    #[test]
    fn test_parse_trigger_time_relative() {
        let clock = Arc::new(VirtualClock::new());
        let now = Utc::now();
        clock.enable_and_set(now);

        let future = parse_trigger_time("+1h", clock.clone()).unwrap();
        assert!((future - now - Duration::hours(1)).num_seconds().abs() < 1);

        let past = parse_trigger_time("-30m", clock.clone()).unwrap();
        assert!((past - now + Duration::minutes(30)).num_seconds().abs() < 1);
    }

    #[test]
    fn test_scenario_store_roundtrip() {
        let scenario = TimeScenario {
            name: "roundtrip".to_string(),
            enabled: true,
            current_time: Some(Utc::now()),
            scale_factor: 1.5,
            scheduled_responses: Vec::new(),
            created_at: Utc::now(),
            description: Some("test".to_string()),
        };

        save_scenario_to_store(scenario.clone());
        let loaded = load_scenario_from_store("roundtrip").expect("scenario");
        assert_eq!(loaded.name, scenario.name);
        assert_eq!(loaded.scale_factor, scenario.scale_factor);
        assert_eq!(loaded.description, scenario.description);
    }
}