mockforge-registry-server 0.3.118

Plugin registry server 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
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
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
//! Hosted Mocks deployment handlers
//!
//! Provides endpoints for deploying, managing, and monitoring cloud-hosted mock services

use axum::{
    extract::{Multipart, Path, State},
    http::HeaderMap,
    Json,
};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::{
    deployment::flyio::FlyioClient,
    error::{ApiError, ApiResult},
    middleware::{
        permission_check::PermissionChecker, permissions::Permission, resolve_org_context, AuthUser,
    },
    models::{
        feature_usage::FeatureType, AuditEventType, DeploymentLog, DeploymentMetrics,
        DeploymentStatus, HostedMock,
    },
    AppState,
};
use tracing::warn;

/// Create a new hosted mock deployment
pub async fn create_deployment(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
    headers: HeaderMap,
    Json(request): Json<CreateDeploymentRequest>,
) -> ApiResult<Json<DeploymentResponse>> {
    let pool = state.db.pool();

    // Resolve org context
    let org_ctx = resolve_org_context(&state, user_id, &headers, None)
        .await
        .map_err(|_| ApiError::InvalidRequest("Organization not found".to_string()))?;

    // Check permission
    let checker = PermissionChecker::new(&state);
    checker
        .require_permission(user_id, org_ctx.org_id, Permission::HostedMockCreate)
        .await?;

    // Check plan limits
    let limits = &org_ctx.org.limits_json;
    let max_hosted_mocks = limits.get("max_hosted_mocks").and_then(|v| v.as_i64()).unwrap_or(0);

    if max_hosted_mocks >= 0 {
        // Count existing active deployments
        let existing = state.store.list_hosted_mocks_by_org(org_ctx.org_id).await?;

        let active_count = existing
            .iter()
            .filter(|m| {
                matches!(m.status(), DeploymentStatus::Active | DeploymentStatus::Deploying)
            })
            .count();

        if active_count as i64 >= max_hosted_mocks {
            return Err(ApiError::InvalidRequest(format!(
                "Hosted mocks limit exceeded. Your plan allows {} active deployments. Upgrade to deploy more.",
                max_hosted_mocks
            )));
        }
    }

    // Validate slug format
    let generated_slug;
    let slug = match request.slug.as_deref() {
        Some(s) => s,
        None => {
            generated_slug = request
                .name
                .to_lowercase()
                .chars()
                .map(|c| {
                    if c.is_alphanumeric() || c == '-' {
                        c
                    } else {
                        '-'
                    }
                })
                .collect::<String>()
                .trim_matches('-')
                .replace("--", "-");
            &generated_slug
        }
    };

    if !slug.chars().all(|c| c.is_alphanumeric() || c == '-') {
        return Err(ApiError::InvalidRequest(
            "Slug must contain only alphanumeric characters and hyphens".to_string(),
        ));
    }

    // Check if slug is already taken
    if state.store.find_hosted_mock_by_slug(org_ctx.org_id, slug).await?.is_some() {
        return Err(ApiError::InvalidRequest(format!(
            "A deployment with slug '{}' already exists",
            slug
        )));
    }

    // Create deployment record
    let deployment = state
        .store
        .create_hosted_mock(
            org_ctx.org_id,
            request.project_id,
            &request.name,
            slug,
            request.description.as_deref(),
            request.config_json,
            request.openapi_spec_url.as_deref(),
            request.region.as_deref(),
        )
        .await?;

    // Log deployment creation
    DeploymentLog::create(
        pool,
        deployment.id,
        "info",
        "Deployment created",
        Some(serde_json::json!({
            "name": request.name,
            "slug": slug,
        })),
    )
    .await
    .map_err(ApiError::Database)?;

    // Mark as pending - the deployment orchestrator will pick it up and deploy it
    // The orchestrator polls for pending/deploying deployments every 10 seconds
    state
        .store
        .update_hosted_mock_status(deployment.id, DeploymentStatus::Pending, None)
        .await?;

    // Track feature usage
    state
        .store
        .record_feature_usage(
            org_ctx.org_id,
            Some(user_id),
            FeatureType::HostedMockDeploy,
            Some(serde_json::json!({
                "deployment_id": deployment.id,
                "name": request.name,
                "slug": slug,
            })),
        )
        .await;

    // Record audit log
    let ip_address = headers
        .get("X-Forwarded-For")
        .or_else(|| headers.get("X-Real-IP"))
        .and_then(|h| h.to_str().ok())
        .map(|s| s.split(',').next().unwrap_or(s).trim());
    let user_agent = headers.get("User-Agent").and_then(|h| h.to_str().ok());

    state
        .store
        .record_audit_event(
            org_ctx.org_id,
            Some(user_id),
            AuditEventType::DeploymentCreated,
            format!("Hosted mock deployment '{}' created", request.name),
            Some(serde_json::json!({
                "deployment_id": deployment.id,
                "name": request.name,
                "slug": slug,
                "project_id": request.project_id,
            })),
            ip_address,
            user_agent,
        )
        .await;

    // Return deployment info
    let deployment = state.store.find_hosted_mock_by_id(deployment.id).await?.ok_or_else(|| {
        ApiError::Internal(anyhow::anyhow!("Failed to retrieve created deployment"))
    })?;

    Ok(Json(DeploymentResponse::from(deployment)))
}

/// List all deployments for the organization
pub async fn list_deployments(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
    headers: HeaderMap,
) -> ApiResult<Json<Vec<DeploymentResponse>>> {
    // Resolve org context
    let org_ctx = resolve_org_context(&state, user_id, &headers, None)
        .await
        .map_err(|_| ApiError::InvalidRequest("Organization not found".to_string()))?;

    // Get all deployments
    let deployments = state.store.list_hosted_mocks_by_org(org_ctx.org_id).await?;

    let responses: Vec<DeploymentResponse> =
        deployments.into_iter().map(DeploymentResponse::from).collect();

    Ok(Json(responses))
}

/// Get deployment details
pub async fn get_deployment(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
    headers: HeaderMap,
    Path(deployment_id): Path<Uuid>,
) -> ApiResult<Json<DeploymentResponse>> {
    // Resolve org context
    let org_ctx = resolve_org_context(&state, user_id, &headers, None)
        .await
        .map_err(|_| ApiError::InvalidRequest("Organization not found".to_string()))?;

    // Get deployment
    let deployment = state
        .store
        .find_hosted_mock_by_id(deployment_id)
        .await?
        .ok_or_else(|| ApiError::InvalidRequest("Deployment not found".to_string()))?;

    // Verify access
    if deployment.org_id != org_ctx.org_id {
        return Err(ApiError::InvalidRequest(
            "You don't have access to this deployment".to_string(),
        ));
    }

    Ok(Json(DeploymentResponse::from(deployment)))
}

/// Update deployment status (internal/admin use)
pub async fn update_deployment_status(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
    headers: HeaderMap,
    Path(deployment_id): Path<Uuid>,
    Json(request): Json<UpdateStatusRequest>,
) -> ApiResult<Json<DeploymentResponse>> {
    // Resolve org context
    let org_ctx = resolve_org_context(&state, user_id, &headers, None)
        .await
        .map_err(|_| ApiError::InvalidRequest("Organization not found".to_string()))?;

    // Check permission
    let checker = PermissionChecker::new(&state);
    checker
        .require_permission(user_id, org_ctx.org_id, Permission::HostedMockUpdate)
        .await?;

    // Get deployment
    let deployment = state
        .store
        .find_hosted_mock_by_id(deployment_id)
        .await?
        .ok_or_else(|| ApiError::InvalidRequest("Deployment not found".to_string()))?;

    // Verify access
    if deployment.org_id != org_ctx.org_id {
        return Err(ApiError::InvalidRequest(
            "You don't have access to this deployment".to_string(),
        ));
    }

    // Update status
    let status = DeploymentStatus::from_str(&request.status)
        .ok_or_else(|| ApiError::InvalidRequest("Invalid status".to_string()))?;

    state
        .store
        .update_hosted_mock_status(deployment_id, status, request.error_message.as_deref())
        .await?;

    // Update URLs if provided
    if request.deployment_url.is_some() || request.internal_url.is_some() {
        state
            .store
            .update_hosted_mock_urls(
                deployment_id,
                request.deployment_url.as_deref(),
                request.internal_url.as_deref(),
            )
            .await?;
    }

    // Get updated deployment
    let deployment = state.store.find_hosted_mock_by_id(deployment_id).await?.ok_or_else(|| {
        ApiError::Internal(anyhow::anyhow!("Failed to retrieve updated deployment"))
    })?;

    // Send deployment status notification email (non-blocking)
    if let Ok(Some(org)) = state.store.find_organization_by_id(deployment.org_id).await {
        if let Ok(Some(owner)) = state.store.find_user_by_id(org.owner_id).await {
            let status_str = format!("{:?}", deployment.status()).to_lowercase();
            let email_msg = crate::email::EmailService::generate_deployment_status_email(
                &owner.username,
                &owner.email,
                &deployment.name,
                &status_str,
                deployment.deployment_url.as_deref(),
                request.error_message.as_deref(),
            );

            tokio::spawn(async move {
                match crate::email::EmailService::from_env() {
                    Ok(email_service) => {
                        if let Err(e) = email_service.send(email_msg).await {
                            tracing::warn!("Failed to send deployment status email: {}", e);
                        }
                    }
                    Err(e) => {
                        tracing::warn!("Failed to create email service: {}", e);
                    }
                }
            });
        }
    }

    Ok(Json(DeploymentResponse::from(deployment)))
}

/// Delete a deployment
pub async fn delete_deployment(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
    headers: HeaderMap,
    Path(deployment_id): Path<Uuid>,
) -> ApiResult<Json<serde_json::Value>> {
    let pool = state.db.pool();

    // Resolve org context
    let org_ctx = resolve_org_context(&state, user_id, &headers, None)
        .await
        .map_err(|_| ApiError::InvalidRequest("Organization not found".to_string()))?;

    // Check permission
    let checker = PermissionChecker::new(&state);
    checker
        .require_permission(user_id, org_ctx.org_id, Permission::HostedMockDelete)
        .await?;

    // Get deployment
    let deployment = state
        .store
        .find_hosted_mock_by_id(deployment_id)
        .await?
        .ok_or_else(|| ApiError::InvalidRequest("Deployment not found".to_string()))?;

    // Verify access
    if deployment.org_id != org_ctx.org_id {
        return Err(ApiError::InvalidRequest(
            "You don't have access to this deployment".to_string(),
        ));
    }

    // Record audit log before deletion
    let ip_address = headers
        .get("X-Forwarded-For")
        .or_else(|| headers.get("X-Real-IP"))
        .and_then(|h| h.to_str().ok())
        .map(|s| s.split(',').next().unwrap_or(s).trim());
    let user_agent = headers.get("User-Agent").and_then(|h| h.to_str().ok());

    state
        .store
        .record_audit_event(
            org_ctx.org_id,
            Some(user_id),
            AuditEventType::DeploymentDeleted,
            format!("Hosted mock deployment '{}' deleted", deployment.name),
            Some(serde_json::json!({
                "deployment_id": deployment.id,
                "name": deployment.name,
                "slug": deployment.slug,
            })),
            ip_address,
            user_agent,
        )
        .await;

    // Update status to deleting before cleanup
    state
        .store
        .update_hosted_mock_status(deployment_id, DeploymentStatus::Deleting, None)
        .await?;

    // Trigger actual deletion (stop service, cleanup resources, etc.)
    // Try to delete from Fly.io if configured
    if let Ok(flyio_token) = std::env::var("FLYIO_API_TOKEN") {
        let flyio_client = FlyioClient::new(flyio_token);

        // Generate app name (same as in orchestrator)
        let app_name = format!(
            "mockforge-{}-{}",
            deployment
                .org_id
                .to_string()
                .replace("-", "")
                .chars()
                .take(8)
                .collect::<String>(),
            deployment.slug
        );

        // Try to get machine_id from metadata
        let machine_id = deployment.metadata_json.get("flyio_machine_id").and_then(|v| v.as_str());

        if let Some(machine_id) = machine_id {
            // Delete the specific machine
            match flyio_client.delete_machine(&app_name, machine_id).await {
                Ok(_) => {
                    DeploymentLog::create(
                        pool,
                        deployment_id,
                        "info",
                        &format!("Deleted Fly.io machine: {}", machine_id),
                        None,
                    )
                    .await
                    .ok();
                }
                Err(e) => {
                    warn!("Failed to delete Fly.io machine {}: {}", machine_id, e);
                    DeploymentLog::create(
                        pool,
                        deployment_id,
                        "warning",
                        &format!("Failed to delete Fly.io machine: {}", e),
                        None,
                    )
                    .await
                    .ok();
                    // Continue with app deletion and database deletion
                }
            }
        } else {
            // Machine ID not found in metadata, try to list and delete all machines
            warn!(
                "Machine ID not found in metadata for deployment {}, attempting to list machines",
                deployment_id
            );
            match flyio_client.list_machines(&app_name).await {
                Ok(machines) => {
                    for machine in machines {
                        if let Err(e) = flyio_client.delete_machine(&app_name, &machine.id).await {
                            warn!("Failed to delete Fly.io machine {}: {}", machine.id, e);
                        } else {
                            DeploymentLog::create(
                                pool,
                                deployment_id,
                                "info",
                                &format!("Deleted Fly.io machine: {}", machine.id),
                                None,
                            )
                            .await
                            .ok();
                        }
                    }
                }
                Err(e) => {
                    warn!("Failed to list Fly.io machines for app {}: {}", app_name, e);
                    // Continue with app deletion and database deletion
                }
            }
        }

        // Delete the Fly.io app itself to avoid empty apps piling up
        match flyio_client.delete_app(&app_name).await {
            Ok(_) => {
                DeploymentLog::create(
                    pool,
                    deployment_id,
                    "info",
                    &format!("Deleted Fly.io app: {}", app_name),
                    None,
                )
                .await
                .ok();
            }
            Err(e) => {
                warn!("Failed to delete Fly.io app {}: {}", app_name, e);
            }
        }
    }

    // Soft delete from database
    state.store.delete_hosted_mock(deployment_id).await?;

    DeploymentLog::create(pool, deployment_id, "info", "Deployment deleted successfully", None)
        .await
        .ok(); // Log but don't fail on log error

    Ok(Json(serde_json::json!({
        "success": true,
        "message": "Deployment deleted"
    })))
}

/// Request body for redeployment (all fields optional)
#[derive(Debug, Deserialize, Default)]
pub struct RedeployRequest {
    /// Updated OpenAPI spec (replaces existing config)
    pub config_json: Option<serde_json::Value>,
    /// Updated spec URL
    pub openapi_spec_url: Option<String>,
}

/// Redeploy an existing hosted mock deployment
///
/// Updates the machine image and optionally the spec, then restarts.
pub async fn redeploy_deployment(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
    headers: HeaderMap,
    Path(deployment_id): Path<Uuid>,
    body: Option<Json<RedeployRequest>>,
) -> ApiResult<Json<serde_json::Value>> {
    let pool = state.db.pool();

    // Resolve org context
    let org_ctx = resolve_org_context(&state, user_id, &headers, None)
        .await
        .map_err(|_| ApiError::InvalidRequest("Organization not found".to_string()))?;

    // Check permission (reuse deploy permission)
    let checker = PermissionChecker::new(&state);
    checker
        .require_permission(user_id, org_ctx.org_id, Permission::HostedMockCreate)
        .await?;
    // pool kept for DeploymentLog + the spawned redeploy orchestration task below

    // Get existing deployment
    let deployment = state
        .store
        .find_hosted_mock_by_id(deployment_id)
        .await?
        .ok_or_else(|| ApiError::InvalidRequest("Deployment not found".to_string()))?;

    // Verify ownership
    if deployment.org_id != org_ctx.org_id {
        return Err(ApiError::InvalidRequest("Deployment not found".to_string()));
    }

    // Only allow redeployment of active or failed deployments
    let status = deployment.status();
    if !matches!(status, DeploymentStatus::Active | DeploymentStatus::Failed) {
        return Err(ApiError::InvalidRequest(format!(
            "Cannot redeploy a deployment with status '{}'. Must be 'active' or 'failed'.",
            status
        )));
    }

    // Update spec if provided
    let request = body.map(|b| b.0).unwrap_or_default();
    if request.config_json.is_some() || request.openapi_spec_url.is_some() {
        let mut query = String::from("UPDATE hosted_mocks SET updated_at = NOW()");
        let mut param_count = 0;

        if request.config_json.is_some() {
            param_count += 1;
            query.push_str(&format!(", config_json = ${}", param_count));
        }
        if request.openapi_spec_url.is_some() {
            param_count += 1;
            query.push_str(&format!(", openapi_spec_url = ${}", param_count));
        }
        param_count += 1;
        query.push_str(&format!(" WHERE id = ${}", param_count));

        let mut q = sqlx::query(&query);
        if let Some(ref config) = request.config_json {
            q = q.bind(config);
        }
        if let Some(ref spec_url) = request.openapi_spec_url {
            q = q.bind(spec_url);
        }
        q = q.bind(deployment_id);
        q.execute(pool).await.map_err(|e| {
            ApiError::Internal(anyhow::anyhow!("Failed to update deployment: {}", e))
        })?;
    }

    // Update status to deploying
    state
        .store
        .update_hosted_mock_status(deployment_id, DeploymentStatus::Deploying, None)
        .await?;

    DeploymentLog::create(pool, deployment_id, "info", "Redeployment initiated", None)
        .await
        .ok();

    // Trigger redeployment in background
    let pool_clone = pool.clone();
    let deployment_id_clone = deployment_id;
    tokio::spawn(async move {
        let pool = &pool_clone;

        // Fetch the updated deployment
        let updated_deployment = match HostedMock::find_by_id(pool, deployment_id_clone).await {
            Ok(Some(d)) => d,
            Ok(None) => {
                tracing::error!("Deployment {} not found during redeploy", deployment_id_clone);
                return;
            }
            Err(e) => {
                tracing::error!(
                    "Failed to fetch deployment {} for redeploy: {}",
                    deployment_id_clone,
                    e
                );
                return;
            }
        };

        // Try to redeploy via Fly.io if configured
        if let Ok(flyio_token) = std::env::var("FLYIO_API_TOKEN") {
            let flyio_client = FlyioClient::new(flyio_token);

            let machine_id = updated_deployment
                .metadata_json
                .get("flyio_machine_id")
                .and_then(|v| v.as_str());

            if let Some(machine_id) = machine_id {
                let app_name = format!(
                    "mockforge-{}-{}",
                    updated_deployment
                        .org_id
                        .to_string()
                        .replace('-', "")
                        .chars()
                        .take(8)
                        .collect::<String>(),
                    updated_deployment.slug
                );

                // Build updated machine config
                let mut env = std::collections::HashMap::new();
                env.insert(
                    "MOCKFORGE_DEPLOYMENT_ID".to_string(),
                    updated_deployment.id.to_string(),
                );
                env.insert("MOCKFORGE_ORG_ID".to_string(), updated_deployment.org_id.to_string());
                if let Ok(config_str) = serde_json::to_string(&updated_deployment.config_json) {
                    env.insert("MOCKFORGE_CONFIG".to_string(), config_str);
                }
                env.insert("PORT".to_string(), "3000".to_string());

                if let Some(ref spec_url) = updated_deployment.openapi_spec_url {
                    env.insert("MOCKFORGE_OPENAPI_SPEC_URL".to_string(), spec_url.clone());
                }

                let image = std::env::var("MOCKFORGE_DOCKER_IMAGE")
                    .unwrap_or_else(|_| "ghcr.io/saasy-solutions/mockforge:latest".to_string());

                use crate::deployment::flyio::{
                    FlyioCheck, FlyioMachineConfig, FlyioPort, FlyioRegistryAuth, FlyioService,
                };

                let services = vec![FlyioService {
                    protocol: "tcp".to_string(),
                    internal_port: 3000,
                    ports: vec![
                        FlyioPort {
                            port: 80,
                            handlers: vec!["http".to_string()],
                        },
                        FlyioPort {
                            port: 443,
                            handlers: vec!["tls".to_string(), "http".to_string()],
                        },
                    ],
                }];

                let mut checks = std::collections::HashMap::new();
                checks.insert(
                    "alive".to_string(),
                    FlyioCheck {
                        check_type: "http".to_string(),
                        port: 3000,
                        grace_period: "10s".to_string(),
                        interval: "15s".to_string(),
                        method: "GET".to_string(),
                        timeout: "2s".to_string(),
                        tls_skip_verify: false,
                        path: Some("/health/live".to_string()),
                    },
                );

                let machine_config = FlyioMachineConfig {
                    image,
                    env,
                    services,
                    checks: Some(checks),
                };

                // Build registry auth
                let registry_auth = if let (Ok(server), Ok(username), Ok(password)) = (
                    std::env::var("DOCKER_REGISTRY_SERVER"),
                    std::env::var("DOCKER_REGISTRY_USERNAME"),
                    std::env::var("DOCKER_REGISTRY_PASSWORD"),
                ) {
                    Some(FlyioRegistryAuth {
                        server,
                        username,
                        password,
                    })
                } else if machine_config.image.starts_with("registry.fly.io/") {
                    Some(FlyioRegistryAuth {
                        server: "registry.fly.io".to_string(),
                        username: "x".to_string(),
                        password: flyio_client.api_token().to_string(),
                    })
                } else {
                    None
                };

                match flyio_client
                    .update_machine(&app_name, machine_id, machine_config, registry_auth)
                    .await
                {
                    Ok(_) => {
                        let _ = DeploymentLog::create(
                            pool,
                            deployment_id_clone,
                            "info",
                            "Machine updated and restarting",
                            None,
                        )
                        .await;
                    }
                    Err(e) => {
                        tracing::error!("Redeployment failed for {}: {:#}", deployment_id_clone, e);
                        let _ = HostedMock::update_status(
                            pool,
                            deployment_id_clone,
                            DeploymentStatus::Failed,
                            Some(&format!("Redeployment failed: {}", e)),
                        )
                        .await;
                        let _ = DeploymentLog::create(
                            pool,
                            deployment_id_clone,
                            "error",
                            &format!("Redeployment failed: {}", e),
                            None,
                        )
                        .await;
                        return;
                    }
                }
            } else {
                tracing::error!(
                    "No Fly.io machine ID found for deployment {}",
                    deployment_id_clone
                );
                let _ = HostedMock::update_status(
                    pool,
                    deployment_id_clone,
                    DeploymentStatus::Failed,
                    Some("No Fly.io machine ID found in deployment metadata"),
                )
                .await;
                return;
            }
        }

        // Mark as active
        let _ =
            HostedMock::update_status(pool, deployment_id_clone, DeploymentStatus::Active, None)
                .await;

        let _ = DeploymentLog::create(
            pool,
            deployment_id_clone,
            "info",
            "Redeployment completed successfully",
            None,
        )
        .await;

        tracing::info!("Successfully redeployed mock service: {}", deployment_id_clone);
    });

    Ok(Json(serde_json::json!({
        "id": deployment_id,
        "status": "deploying",
        "message": "Redeployment initiated"
    })))
}

fn deployment_app_name(deployment: &HostedMock) -> String {
    format!(
        "mockforge-{}-{}",
        deployment
            .org_id
            .to_string()
            .replace('-', "")
            .chars()
            .take(8)
            .collect::<String>(),
        deployment.slug
    )
}

/// Stop a running hosted mock deployment.
///
/// Gracefully stops the Fly.io machine (without deleting it) and marks
/// the deployment as `stopped`. Only active deployments can be stopped.
pub async fn stop_deployment(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
    headers: HeaderMap,
    Path(deployment_id): Path<Uuid>,
) -> ApiResult<Json<DeploymentResponse>> {
    let pool = state.db.pool();

    let org_ctx = resolve_org_context(&state, user_id, &headers, None)
        .await
        .map_err(|_| ApiError::InvalidRequest("Organization not found".to_string()))?;

    let checker = PermissionChecker::new(&state);
    checker
        .require_permission(user_id, org_ctx.org_id, Permission::HostedMockUpdate)
        .await?;

    let deployment = state
        .store
        .find_hosted_mock_by_id(deployment_id)
        .await?
        .ok_or_else(|| ApiError::InvalidRequest("Deployment not found".to_string()))?;

    if deployment.org_id != org_ctx.org_id {
        return Err(ApiError::InvalidRequest("Deployment not found".to_string()));
    }

    let status = deployment.status();
    if !matches!(status, DeploymentStatus::Active) {
        return Err(ApiError::InvalidRequest(format!(
            "Cannot stop a deployment with status '{}'. Must be 'active'.",
            status
        )));
    }

    if let Ok(flyio_token) = std::env::var("FLYIO_API_TOKEN") {
        let flyio_client = FlyioClient::new(flyio_token);
        let app_name = deployment_app_name(&deployment);
        let machine_id = deployment.metadata_json.get("flyio_machine_id").and_then(|v| v.as_str());

        if let Some(machine_id) = machine_id {
            flyio_client.stop_machine(&app_name, machine_id).await.map_err(|e| {
                ApiError::Internal(anyhow::anyhow!("Failed to stop machine: {}", e))
            })?;
        } else {
            warn!(
                "No Fly.io machine ID found for deployment {}; marking as stopped anyway",
                deployment_id
            );
        }
    }

    state
        .store
        .update_hosted_mock_status(deployment_id, DeploymentStatus::Stopped, None)
        .await?;

    DeploymentLog::create(pool, deployment_id, "info", "Deployment stopped", None)
        .await
        .ok();

    let updated = state.store.find_hosted_mock_by_id(deployment_id).await?.ok_or_else(|| {
        ApiError::Internal(anyhow::anyhow!("Failed to retrieve updated deployment"))
    })?;

    Ok(Json(DeploymentResponse::from(updated)))
}

/// Start a stopped hosted mock deployment.
pub async fn start_deployment(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
    headers: HeaderMap,
    Path(deployment_id): Path<Uuid>,
) -> ApiResult<Json<DeploymentResponse>> {
    let pool = state.db.pool();

    let org_ctx = resolve_org_context(&state, user_id, &headers, None)
        .await
        .map_err(|_| ApiError::InvalidRequest("Organization not found".to_string()))?;

    let checker = PermissionChecker::new(&state);
    checker
        .require_permission(user_id, org_ctx.org_id, Permission::HostedMockUpdate)
        .await?;

    let deployment = state
        .store
        .find_hosted_mock_by_id(deployment_id)
        .await?
        .ok_or_else(|| ApiError::InvalidRequest("Deployment not found".to_string()))?;

    if deployment.org_id != org_ctx.org_id {
        return Err(ApiError::InvalidRequest("Deployment not found".to_string()));
    }

    let status = deployment.status();
    if !matches!(status, DeploymentStatus::Stopped) {
        return Err(ApiError::InvalidRequest(format!(
            "Cannot start a deployment with status '{}'. Must be 'stopped'.",
            status
        )));
    }

    if let Ok(flyio_token) = std::env::var("FLYIO_API_TOKEN") {
        let flyio_client = FlyioClient::new(flyio_token);
        let app_name = deployment_app_name(&deployment);
        let machine_id = deployment.metadata_json.get("flyio_machine_id").and_then(|v| v.as_str());

        if let Some(machine_id) = machine_id {
            flyio_client.start_machine(&app_name, machine_id).await.map_err(|e| {
                ApiError::Internal(anyhow::anyhow!("Failed to start machine: {}", e))
            })?;
        } else {
            return Err(ApiError::InvalidRequest(
                "No Fly.io machine ID found in deployment metadata; cannot start".to_string(),
            ));
        }
    }

    state
        .store
        .update_hosted_mock_status(deployment_id, DeploymentStatus::Active, None)
        .await?;

    DeploymentLog::create(pool, deployment_id, "info", "Deployment started", None)
        .await
        .ok();

    let updated = state.store.find_hosted_mock_by_id(deployment_id).await?.ok_or_else(|| {
        ApiError::Internal(anyhow::anyhow!("Failed to retrieve updated deployment"))
    })?;

    Ok(Json(DeploymentResponse::from(updated)))
}

/// Get deployment logs
pub async fn get_deployment_logs(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
    headers: HeaderMap,
    Path(deployment_id): Path<Uuid>,
) -> ApiResult<Json<Vec<LogResponse>>> {
    let pool = state.db.pool();

    // Resolve org context
    let org_ctx = resolve_org_context(&state, user_id, &headers, None)
        .await
        .map_err(|_| ApiError::InvalidRequest("Organization not found".to_string()))?;

    // Get deployment
    let deployment = HostedMock::find_by_id(pool, deployment_id)
        .await
        .map_err(ApiError::Database)?
        .ok_or_else(|| ApiError::InvalidRequest("Deployment not found".to_string()))?;

    // Verify access
    if deployment.org_id != org_ctx.org_id {
        return Err(ApiError::InvalidRequest(
            "You don't have access to this deployment".to_string(),
        ));
    }

    // Get logs
    let logs = DeploymentLog::find_by_mock(pool, deployment_id, Some(100))
        .await
        .map_err(ApiError::Database)?;

    let responses: Vec<LogResponse> = logs.into_iter().map(LogResponse::from).collect();

    Ok(Json(responses))
}

/// Get deployment metrics
pub async fn get_deployment_metrics(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
    headers: HeaderMap,
    Path(deployment_id): Path<Uuid>,
) -> ApiResult<Json<MetricsResponse>> {
    let pool = state.db.pool();

    // Resolve org context
    let org_ctx = resolve_org_context(&state, user_id, &headers, None)
        .await
        .map_err(|_| ApiError::InvalidRequest("Organization not found".to_string()))?;

    // Get deployment
    let deployment = HostedMock::find_by_id(pool, deployment_id)
        .await
        .map_err(ApiError::Database)?
        .ok_or_else(|| ApiError::InvalidRequest("Deployment not found".to_string()))?;

    // Verify access
    if deployment.org_id != org_ctx.org_id {
        return Err(ApiError::InvalidRequest(
            "You don't have access to this deployment".to_string(),
        ));
    }

    // Get current metrics
    let metrics = DeploymentMetrics::get_or_create_current(pool, deployment_id)
        .await
        .map_err(ApiError::Database)?;

    Ok(Json(MetricsResponse::from(metrics)))
}

/// Upload an OpenAPI spec file for use in a hosted mock deployment
pub async fn upload_spec(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
    headers: HeaderMap,
    mut multipart: Multipart,
) -> ApiResult<Json<SpecUploadResponse>> {
    // Resolve org context
    let org_ctx = resolve_org_context(&state, user_id, &headers, None)
        .await
        .map_err(|_| ApiError::InvalidRequest("Organization not found".to_string()))?;

    // Check permission
    let checker = PermissionChecker::new(&state);
    checker
        .require_permission(user_id, org_ctx.org_id, Permission::HostedMockCreate)
        .await?;

    // Extract file from multipart
    let mut file_data: Option<Vec<u8>> = None;
    let mut file_name = String::from("spec");

    while let Some(field) = multipart
        .next_field()
        .await
        .map_err(|e| ApiError::InvalidRequest(format!("Failed to read multipart field: {}", e)))?
    {
        if field.name() == Some("file") || field.name() == Some("spec") {
            if let Some(name) = field.file_name() {
                file_name =
                    name.to_string().replace(".yaml", "").replace(".yml", "").replace(".json", "");
            }
            let data = field.bytes().await.map_err(|e| {
                ApiError::InvalidRequest(format!("Failed to read file data: {}", e))
            })?;

            // Validate it's valid JSON or YAML OpenAPI spec
            let content = String::from_utf8(data.to_vec()).map_err(|_| {
                ApiError::InvalidRequest("File must be valid UTF-8 text".to_string())
            })?;

            // Try to parse as JSON first, then YAML
            let spec_value: serde_json::Value =
                if let Ok(v) = serde_json::from_str::<serde_json::Value>(&content) {
                    v
                } else if let Ok(v) = serde_yaml::from_str::<serde_json::Value>(&content) {
                    v
                } else {
                    return Err(ApiError::InvalidRequest(
                        "File must be a valid JSON or YAML OpenAPI specification".to_string(),
                    ));
                };

            // Basic OpenAPI validation - check for required fields
            if spec_value.get("openapi").is_none() && spec_value.get("swagger").is_none() {
                return Err(ApiError::InvalidRequest(
                    "File must contain an 'openapi' or 'swagger' field".to_string(),
                ));
            }

            // Always store as JSON
            let json_data = serde_json::to_vec_pretty(&spec_value).map_err(|e| {
                ApiError::Internal(anyhow::anyhow!("Failed to serialize spec: {}", e))
            })?;

            file_data = Some(json_data);
        }
    }

    let data = file_data.ok_or_else(|| {
        ApiError::InvalidRequest("No 'file' or 'spec' field in upload".to_string())
    })?;

    // Upload to storage
    let url = state
        .storage
        .upload_spec(&org_ctx.org_id.to_string(), &file_name, data)
        .await
        .map_err(|e| ApiError::Internal(anyhow::anyhow!("Failed to upload spec: {}", e)))?;

    Ok(Json(SpecUploadResponse { url }))
}

#[derive(Debug, Serialize)]
pub struct SpecUploadResponse {
    pub url: String,
}

// Request/Response types

#[derive(Debug, Deserialize)]
pub struct CreateDeploymentRequest {
    pub name: String,
    pub slug: Option<String>,
    pub description: Option<String>,
    pub project_id: Option<Uuid>,
    pub config_json: serde_json::Value,
    pub openapi_spec_url: Option<String>,
    pub region: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct UpdateStatusRequest {
    pub status: String,
    pub error_message: Option<String>,
    pub deployment_url: Option<String>,
    pub internal_url: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct DeploymentResponse {
    pub id: Uuid,
    pub org_id: Uuid,
    pub project_id: Option<Uuid>,
    pub name: String,
    pub slug: String,
    pub description: Option<String>,
    pub status: String,
    pub deployment_url: Option<String>,
    pub openapi_spec_url: Option<String>,
    pub region: String,
    pub instance_type: String,
    pub health_status: String,
    pub error_message: Option<String>,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

impl From<HostedMock> for DeploymentResponse {
    fn from(mock: HostedMock) -> Self {
        let status = mock.status().to_string();
        let health_status = mock.health_status().to_string();
        Self {
            id: mock.id,
            org_id: mock.org_id,
            project_id: mock.project_id,
            name: mock.name,
            slug: mock.slug,
            description: mock.description,
            status,
            deployment_url: mock.deployment_url,
            openapi_spec_url: mock.openapi_spec_url,
            region: mock.region,
            instance_type: mock.instance_type,
            health_status,
            error_message: mock.error_message,
            created_at: mock.created_at,
            updated_at: mock.updated_at,
        }
    }
}

#[derive(Debug, Serialize)]
pub struct LogResponse {
    pub id: Uuid,
    pub level: String,
    pub message: String,
    pub metadata: serde_json::Value,
    pub created_at: chrono::DateTime<chrono::Utc>,
}

impl From<DeploymentLog> for LogResponse {
    fn from(log: DeploymentLog) -> Self {
        Self {
            id: log.id,
            level: log.level,
            message: log.message,
            metadata: log.metadata_json,
            created_at: log.created_at,
        }
    }
}

#[derive(Debug, Serialize)]
pub struct MetricsResponse {
    pub requests: i64,
    pub requests_2xx: i64,
    pub requests_4xx: i64,
    pub requests_5xx: i64,
    pub egress_bytes: i64,
    pub avg_response_time_ms: i64,
    pub period_start: chrono::NaiveDate,
}

impl From<DeploymentMetrics> for MetricsResponse {
    fn from(metrics: DeploymentMetrics) -> Self {
        Self {
            requests: metrics.requests,
            requests_2xx: metrics.requests_2xx,
            requests_4xx: metrics.requests_4xx,
            requests_5xx: metrics.requests_5xx,
            egress_bytes: metrics.egress_bytes,
            avg_response_time_ms: metrics.avg_response_time_ms,
            period_start: metrics.period_start,
        }
    }
}

#[derive(Debug, Deserialize)]
pub struct SetDomainRequest {
    pub domain: String,
}

/// Set a custom domain for a deployment.
///
/// Adds a TLS certificate on the registry server Fly.io app so that
/// `<slug>.<domain>` terminates TLS here, then the proxy fallback
/// handler forwards traffic to the deployment's internal URL.
pub async fn set_domain(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
    headers: HeaderMap,
    Path(deployment_id): Path<Uuid>,
    Json(request): Json<SetDomainRequest>,
) -> ApiResult<Json<serde_json::Value>> {
    let pool = state.db.pool();

    // Resolve org context
    let org_ctx = resolve_org_context(&state, user_id, &headers, None)
        .await
        .map_err(|_| ApiError::InvalidRequest("Organization not found".to_string()))?;

    // Check permission
    let checker = PermissionChecker::new(&state);
    checker
        .require_permission(user_id, org_ctx.org_id, Permission::HostedMockCreate)
        .await?;

    // Get deployment
    let deployment = HostedMock::find_by_id(pool, deployment_id)
        .await
        .map_err(ApiError::Database)?
        .ok_or_else(|| ApiError::InvalidRequest("Deployment not found".to_string()))?;

    // Verify ownership
    if deployment.org_id != org_ctx.org_id {
        return Err(ApiError::InvalidRequest("Deployment not found".to_string()));
    }

    let hostname = format!("{}.{}", deployment.slug, request.domain);

    // Update deployment URL to use the custom domain.
    // A wildcard TLS cert on the registry app covers all subdomains,
    // so no per-deployment certificate management is needed.
    let new_url = format!("https://{}", hostname);
    sqlx::query("UPDATE hosted_mocks SET deployment_url = $1, updated_at = NOW() WHERE id = $2")
        .bind(&new_url)
        .bind(deployment_id)
        .execute(pool)
        .await
        .map_err(|e| {
            ApiError::Internal(anyhow::anyhow!("Failed to update deployment URL: {}", e))
        })?;

    DeploymentLog::create(
        pool,
        deployment_id,
        "info",
        &format!("Custom domain set: {}", hostname),
        None,
    )
    .await
    .ok();

    Ok(Json(serde_json::json!({
        "hostname": hostname,
        "deployment_url": new_url,
    })))
}