rise-deploy 0.16.4

A simple and powerful CLI for deploying containerized applications
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
use super::fuzzy::find_similar_projects;
use super::models::{
    AccessClassInfo, CreateProjectRequest, CreateProjectResponse, GetProjectParams,
    ListAccessClassesResponse, OwnerInfo, Project as ApiProject, ProjectErrorResponse,
    ProjectOwner, ProjectStatus, TeamInfo, UpdateProjectRequest, UpdateProjectResponse, UserInfo,
};
use crate::db::models::User;
use crate::db::{projects, service_accounts, teams as db_teams, users as db_users};
use crate::server::error::{ServerError, ServerErrorExt};
use crate::server::state::AppState;
use axum::{
    extract::{Extension, Path, Query, State},
    http::StatusCode,
    Json,
};
use uuid::Uuid;

/// List available access classes for the deployment controller
pub async fn list_access_classes(
    State(state): State<AppState>,
    Extension(_user): Extension<User>,
) -> Result<Json<ListAccessClassesResponse>, ServerError> {
    let access_classes = state
        .access_classes
        .iter()
        .map(|(id, class)| AccessClassInfo {
            id: id.clone(),
            display_name: class.display_name.clone(),
            description: class.description.clone(),
        })
        .collect();

    Ok(Json(ListAccessClassesResponse { access_classes }))
}

/// Resolve user identifier (UUID or email) to user ID
async fn resolve_user_identifier(
    pool: &sqlx::PgPool,
    identifier: &str,
) -> Result<uuid::Uuid, ServerError> {
    use crate::server::error::ServerErrorExt;

    if let Ok(uuid) = uuid::Uuid::parse_str(identifier) {
        // Valid UUID - verify user exists
        db_users::find_by_id(pool, uuid)
            .await
            .internal_err("Failed to lookup user")?
            .ok_or_else(|| ServerError::not_found(format!("User not found: {}", identifier)))
            .map(|u| u.id)
    } else {
        // Treat as email - look up user
        db_users::find_by_email(pool, identifier)
            .await
            .internal_err("Failed to lookup user")?
            .ok_or_else(|| ServerError::not_found(format!("User not found: {}", identifier)))
            .map(|u| u.id)
    }
}

/// Resolve team identifier (UUID or name) to team ID
async fn resolve_team_identifier(
    pool: &sqlx::PgPool,
    identifier: &str,
) -> Result<uuid::Uuid, ServerError> {
    use crate::server::error::ServerErrorExt;

    if let Ok(uuid) = uuid::Uuid::parse_str(identifier) {
        // Valid UUID - verify team exists
        db_teams::find_by_id(pool, uuid)
            .await
            .internal_err("Failed to lookup team")?
            .ok_or_else(|| ServerError::not_found(format!("Team not found: {}", identifier)))
            .map(|t| t.id)
    } else {
        // Treat as team name - look up team
        db_teams::find_by_name(pool, identifier)
            .await
            .internal_err("Failed to lookup team")?
            .ok_or_else(|| ServerError::not_found(format!("Team not found: {}", identifier)))
            .map(|t| t.id)
    }
}

pub async fn create_project(
    State(state): State<AppState>,
    Extension(user): Extension<User>,
    Json(payload): Json<CreateProjectRequest>,
) -> Result<Json<CreateProjectResponse>, ServerError> {
    // Validate access_class against configured access classes
    let is_valid_access_class = state.access_classes.contains_key(&payload.access_class);

    if !is_valid_access_class {
        let available = state
            .access_classes
            .keys()
            .cloned()
            .collect::<Vec<_>>()
            .join(", ");

        return Err(ServerError::bad_request(format!(
            "Invalid access class '{}'. Available: {}",
            payload.access_class, available
        )));
    }

    // Validate owner - exactly one of owner_user or owner_team must be set
    let (owner_user_id, owner_team_id) = match &payload.owner {
        ProjectOwner::User(user_id) => {
            let uuid =
                Uuid::parse_str(user_id).server_err(StatusCode::BAD_REQUEST, "Invalid user ID")?;
            (Some(uuid), None)
        }
        ProjectOwner::Team(team_id) => {
            let uuid =
                Uuid::parse_str(team_id).server_err(StatusCode::BAD_REQUEST, "Invalid team ID")?;

            // Verify user is a member of the team
            let is_member = db_teams::is_member(&state.db_pool, uuid, user.id)
                .await
                .internal_err("Failed to check team membership")
                .map_err(|e| {
                    e.with_context("team_id", uuid.to_string())
                        .with_context("user_id", user.id.to_string())
                })?;

            if !is_member {
                return Err(ServerError::forbidden("You are not a member of this team"));
            }

            (None, Some(uuid))
        }
    };

    tracing::info!(
        "Creating project '{}' for user {}",
        payload.name,
        user.email
    );

    let project = projects::create(
        &state.db_pool,
        &payload.name,
        crate::db::models::ProjectStatus::Stopped,
        payload.access_class,
        owner_user_id,
        owner_team_id,
    )
    .await
    .map_err(|e| {
        if e.to_string().contains("duplicate key") || e.to_string().contains("unique constraint") {
            ServerError::new(
                StatusCode::CONFLICT,
                format!("Project '{}' already exists", &payload.name),
            )
        } else {
            ServerError::internal_anyhow(e, "Failed to create project")
                .with_context("project_name", &payload.name)
                .with_context("user_email", &user.email)
        }
    })?;

    // Transaction for app user/team additions
    use crate::server::error::ServerErrorExt;

    let mut tx = state
        .db_pool
        .begin()
        .await
        .internal_err("Failed to start transaction")?;

    // Add app users if provided
    for user_identifier in &payload.app_users {
        let user_id = resolve_user_identifier(&state.db_pool, user_identifier).await?;
        crate::db::project_app_users::add_user(&mut *tx, project.id, user_id)
            .await
            .internal_err("Failed to add app user")?;
    }

    // Add app teams if provided
    for team_identifier in &payload.app_teams {
        let team_id = resolve_team_identifier(&state.db_pool, team_identifier).await?;
        crate::db::project_app_users::add_team(&mut *tx, project.id, team_id)
            .await
            .internal_err("Failed to add app team")?;
    }

    tx.commit()
        .await
        .internal_err("Failed to commit transaction")?;

    let owner_info = resolve_owner_info(&state, &project)
        .await
        .map_err(|e| ServerError::internal(format!("Failed to resolve owner info: {}", e)))?;

    Ok(Json(CreateProjectResponse {
        project: convert_project(project, owner_info),
    }))
}

pub async fn list_projects(
    State(state): State<AppState>,
    Extension(user): Extension<User>,
) -> Result<Json<Vec<ApiProject>>, ServerError> {
    // Admins can see all projects, others only see projects they have access to
    let projects = if state.is_admin(&user.email) {
        projects::list(&state.db_pool, None)
            .await
            .internal_err("Failed to list projects")?
    } else {
        projects::list_accessible_by_user(&state.db_pool, user.id)
            .await
            .internal_err("Failed to list projects")
            .map_err(|e| e.with_context("user_id", user.id.to_string()))?
    };

    // Batch fetch active deployment info for efficiency
    let project_ids: Vec<uuid::Uuid> = projects.iter().map(|p| p.id).collect();
    let active_deployment_info =
        projects::get_active_deployment_info_batch(&state.db_pool, &project_ids)
            .await
            .internal_err("Failed to get active deployment info")?;

    // Batch fetch active deployments to calculate URLs
    let deployment_ids: Vec<Uuid> = active_deployment_info
        .values()
        .filter_map(|info| info.as_ref().map(|i| i.id))
        .collect();

    let deployments_map = if !deployment_ids.is_empty() {
        crate::db::deployments::get_deployments_batch(&state.db_pool, &deployment_ids)
            .await
            .internal_err("Failed to get deployments")?
    } else {
        std::collections::HashMap::new()
    };

    // Batch fetch owner information (user emails and team names)
    let user_ids: Vec<Uuid> = projects.iter().filter_map(|p| p.owner_user_id).collect();
    let team_ids: Vec<Uuid> = projects.iter().filter_map(|p| p.owner_team_id).collect();

    let user_emails = if !user_ids.is_empty() {
        db_users::get_emails_batch(&state.db_pool, &user_ids)
            .await
            .internal_err("Failed to get user emails")?
    } else {
        std::collections::HashMap::new()
    };

    let team_names = if !team_ids.is_empty() {
        db_teams::get_names_batch(&state.db_pool, &team_ids)
            .await
            .internal_err("Failed to get team names")?
    } else {
        std::collections::HashMap::new()
    };

    // Calculate URLs for all projects
    let mut api_projects = Vec::new();
    for project in projects {
        let (active_deployment_status, default_url, primary_url, custom_domain_urls) =
            if let Some(Some(info)) = active_deployment_info.get(&project.id) {
                if let Some(deployment) = deployments_map.get(&info.id) {
                    match state
                        .deployment_backend
                        .get_deployment_urls(deployment, &project)
                        .await
                    {
                        Ok(urls) => (
                            Some(info.status.to_string()),
                            Some(urls.default_url),
                            Some(urls.primary_url),
                            urls.custom_domain_urls,
                        ),
                        Err(e) => {
                            return Err(ServerError::internal_anyhow(
                                e,
                                "Failed to calculate deployment URLs",
                            )
                            .with_context("project_name", &project.name));
                        }
                    }
                } else {
                    (Some(info.status.to_string()), None, None, vec![])
                }
            } else {
                (None, None, None, vec![])
            };

        let owner = if let Some(user_id) = project.owner_user_id {
            user_emails.get(&user_id).map(|email| {
                OwnerInfo::User(UserInfo {
                    id: user_id.to_string(),
                    email: email.clone(),
                })
            })
        } else if let Some(team_id) = project.owner_team_id {
            team_names.get(&team_id).map(|name| {
                OwnerInfo::Team(TeamInfo {
                    id: team_id.to_string(),
                    name: name.clone(),
                })
            })
        } else {
            None
        };

        api_projects.push(ApiProject {
            id: project.id.to_string(),
            created: project.created_at.to_rfc3339(),
            updated: project.updated_at.to_rfc3339(),
            name: project.name,
            status: ProjectStatus::from(project.status),
            access_class: project.access_class,
            owner,
            active_deployment_status,
            default_url,
            primary_url,
            custom_domain_urls,
            deployment_groups: None, // Not populated in list view for performance
            finalizers: vec![],      // Not populated in list view for performance
            app_users: vec![],       // Not populated in list view for performance
            app_teams: vec![],       // Not populated in list view for performance
        });
    }

    Ok(Json(api_projects))
}

pub async fn get_project(
    State(state): State<AppState>,
    Extension(user): Extension<User>,
    Path(id_or_name): Path<String>,
    Query(params): Query<GetProjectParams>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<ProjectErrorResponse>)> {
    // Resolve project by ID or name
    let project = resolve_project(&state, &id_or_name, params.by_id).await?;

    // Check read permission
    let can_read = check_read_permission(&state, &project, &user)
        .await
        .map_err(|e| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ProjectErrorResponse {
                    error: format!("Failed to check permissions: {}", e),
                    suggestions: None,
                }),
            )
        })?;

    if !can_read {
        // Use 404 to hide project existence from unauthorized users
        return Err((
            StatusCode::NOT_FOUND,
            Json(ProjectErrorResponse {
                error: format!("Project '{}' not found", id_or_name),
                suggestions: None,
            }),
        ));
    }

    // Calculate deployment URLs if there's an active deployment
    let (default_url, primary_url, custom_domain_urls) =
        match crate::db::deployments::get_active_deployments_for_project(&state.db_pool, project.id)
            .await
        {
            Ok(active_deployments) => {
                // Find the active deployment in the default group
                if let Some(deployment) = active_deployments.iter().find(|d| {
                    d.deployment_group
                        == crate::server::deployment::models::DEFAULT_DEPLOYMENT_GROUP
                }) {
                    match state
                        .deployment_backend
                        .get_deployment_urls(deployment, &project)
                        .await
                    {
                        Ok(urls) => (
                            Some(urls.default_url),
                            Some(urls.primary_url),
                            urls.custom_domain_urls,
                        ),
                        Err(e) => {
                            return Err((
                                StatusCode::INTERNAL_SERVER_ERROR,
                                Json(ProjectErrorResponse {
                                    error: format!("Failed to calculate URLs: {}", e),
                                    suggestions: None,
                                }),
                            ));
                        }
                    }
                } else {
                    (None, None, vec![])
                }
            }
            Err(e) => {
                return Err((
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(ProjectErrorResponse {
                        error: format!("Failed to get active deployments: {}", e),
                        suggestions: None,
                    }),
                ));
            }
        };

    // Resolve owner info
    let owner_info = resolve_owner_info(&state, &project).await.map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ProjectErrorResponse {
                error: format!("Failed to resolve owner info: {}", e),
                suggestions: None,
            }),
        )
    })?;

    let mut api_project = convert_project(project.clone(), owner_info);
    api_project.default_url = default_url;
    api_project.primary_url = primary_url;
    api_project.custom_domain_urls = custom_domain_urls;

    // Get active deployment groups
    let deployment_groups =
        crate::db::deployments::get_active_deployment_groups(&state.db_pool, project.id)
            .await
            .map_err(|e| {
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(ProjectErrorResponse {
                        error: format!("Failed to get deployment groups: {}", e),
                        suggestions: None,
                    }),
                )
            })?;
    api_project.deployment_groups = if deployment_groups.is_empty() {
        None
    } else {
        Some(deployment_groups)
    };

    // Load app users and teams
    let (app_users, app_teams) = load_app_users_for_project(&state, project.id)
        .await
        .map_err(|e| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ProjectErrorResponse {
                    error: format!("Failed to load app users: {}", e),
                    suggestions: None,
                }),
            )
        })?;
    api_project.app_users = app_users;
    api_project.app_teams = app_teams;

    Ok(Json(serde_json::to_value(api_project).unwrap()))
}

pub async fn update_project(
    State(state): State<AppState>,
    Extension(user): Extension<User>,
    Path(id_or_name): Path<String>,
    Query(params): Query<GetProjectParams>,
    Json(payload): Json<UpdateProjectRequest>,
) -> Result<Json<UpdateProjectResponse>, (StatusCode, Json<ProjectErrorResponse>)> {
    // Resolve project by ID or name
    let project = resolve_project(&state, &id_or_name, params.by_id).await?;

    // Check write permission
    let can_write = check_write_permission(&state, &project, &user)
        .await
        .map_err(|e| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ProjectErrorResponse {
                    error: format!("Failed to check permissions: {}", e),
                    suggestions: None,
                }),
            )
        })?;

    if !can_write {
        return Err((
            StatusCode::FORBIDDEN,
            Json(ProjectErrorResponse {
                error: "You do not have permission to update this project".to_string(),
                suggestions: None,
            }),
        ));
    }

    // Service accounts cannot update projects
    let is_sa = service_accounts::is_service_account(&state.db_pool, user.id)
        .await
        .map_err(|e| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ProjectErrorResponse {
                    error: format!("Failed to check service account status: {}", e),
                    suggestions: None,
                }),
            )
        })?;

    if is_sa {
        return Err((
            StatusCode::FORBIDDEN,
            Json(ProjectErrorResponse {
                error: "Service accounts cannot modify projects".to_string(),
                suggestions: None,
            }),
        ));
    }

    // Update project fields
    let mut updated_project = project;

    // Update owner if provided
    if let Some(owner) = payload.owner {
        let (owner_user_id, owner_team_id) = match owner {
            ProjectOwner::User(user_identifier) => {
                // Try to resolve as email first, then as UUID
                let user = if let Ok(uuid) = Uuid::parse_str(&user_identifier) {
                    // Valid UUID - look up by ID
                    db_users::find_by_id(&state.db_pool, uuid)
                        .await
                        .map_err(|e| {
                            (
                                StatusCode::INTERNAL_SERVER_ERROR,
                                Json(ProjectErrorResponse {
                                    error: format!("Failed to verify user: {}", e),
                                    suggestions: None,
                                }),
                            )
                        })?
                } else {
                    // Not a UUID - treat as email
                    db_users::find_by_email(&state.db_pool, &user_identifier)
                        .await
                        .map_err(|e| {
                            (
                                StatusCode::INTERNAL_SERVER_ERROR,
                                Json(ProjectErrorResponse {
                                    error: format!("Failed to verify user: {}", e),
                                    suggestions: None,
                                }),
                            )
                        })?
                };

                let user = user.ok_or_else(|| {
                    (
                        StatusCode::NOT_FOUND,
                        Json(ProjectErrorResponse {
                            error: format!("User '{}' not found", user_identifier),
                            suggestions: None,
                        }),
                    )
                })?;

                (Some(user.id), None)
            }
            ProjectOwner::Team(team_identifier) => {
                // Try to resolve as name first, then as UUID
                let team = if let Ok(uuid) = Uuid::parse_str(&team_identifier) {
                    // Valid UUID - look up by ID
                    db_teams::find_by_id(&state.db_pool, uuid)
                        .await
                        .map_err(|e| {
                            (
                                StatusCode::INTERNAL_SERVER_ERROR,
                                Json(ProjectErrorResponse {
                                    error: format!("Failed to verify team: {}", e),
                                    suggestions: None,
                                }),
                            )
                        })?
                } else {
                    // Not a UUID - treat as team name
                    db_teams::find_by_name(&state.db_pool, &team_identifier)
                        .await
                        .map_err(|e| {
                            (
                                StatusCode::INTERNAL_SERVER_ERROR,
                                Json(ProjectErrorResponse {
                                    error: format!("Failed to verify team: {}", e),
                                    suggestions: None,
                                }),
                            )
                        })?
                };

                let team = team.ok_or_else(|| {
                    (
                        StatusCode::NOT_FOUND,
                        Json(ProjectErrorResponse {
                            error: format!("Team '{}' not found", team_identifier),
                            suggestions: None,
                        }),
                    )
                })?;

                // Verify the requesting user is a member of the team they're transferring to
                let is_member = db_teams::is_member(&state.db_pool, team.id, user.id)
                    .await
                    .map_err(|e| {
                        (
                            StatusCode::INTERNAL_SERVER_ERROR,
                            Json(ProjectErrorResponse {
                                error: format!("Failed to check team membership: {}", e),
                                suggestions: None,
                            }),
                        )
                    })?;

                if !is_member {
                    return Err((
                        StatusCode::FORBIDDEN,
                        Json(ProjectErrorResponse {
                            error: format!(
                                "You must be a member of team '{}' to transfer projects to it",
                                team.name
                            ),
                            suggestions: None,
                        }),
                    ));
                }

                (None, Some(team.id))
            }
        };

        updated_project = projects::update_owner(
            &state.db_pool,
            updated_project.id,
            owner_user_id,
            owner_team_id,
        )
        .await
        .map_err(|e| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ProjectErrorResponse {
                    error: format!("Failed to update project owner: {}", e),
                    suggestions: None,
                }),
            )
        })?;
    }

    // Update access_class if provided
    if let Some(access_class) = payload.access_class {
        // Validate against configured access classes
        let is_valid = state.access_classes.contains_key(&access_class);

        if !is_valid {
            let available = state
                .access_classes
                .keys()
                .cloned()
                .collect::<Vec<_>>()
                .join(", ");

            return Err((
                StatusCode::BAD_REQUEST,
                Json(ProjectErrorResponse {
                    error: format!(
                        "Invalid access class '{}'. Available: {}",
                        access_class, available
                    ),
                    suggestions: None,
                }),
            ));
        }

        updated_project =
            projects::update_access_class(&state.db_pool, updated_project.id, access_class)
                .await
                .map_err(|e| {
                    (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        Json(ProjectErrorResponse {
                            error: format!("Failed to update project access class: {}", e),
                            suggestions: None,
                        }),
                    )
                })?;
    }

    // Update app users if provided
    if let Some(app_users) = payload.app_users {
        let mut tx = state.db_pool.begin().await.map_err(|e| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ProjectErrorResponse {
                    error: format!("Failed to start transaction: {}", e),
                    suggestions: None,
                }),
            )
        })?;

        // Remove all existing app users
        let existing_users = crate::db::project_app_users::list_users(&mut *tx, updated_project.id)
            .await
            .map_err(|e| {
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(ProjectErrorResponse {
                        error: format!("Failed to list existing app users: {}", e),
                        suggestions: None,
                    }),
                )
            })?;

        for user_id in existing_users {
            crate::db::project_app_users::remove_user(&mut *tx, updated_project.id, user_id)
                .await
                .map_err(|e| {
                    (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        Json(ProjectErrorResponse {
                            error: format!("Failed to remove app user: {}", e),
                            suggestions: None,
                        }),
                    )
                })?;
        }

        // Add new app users
        for user_identifier in &app_users {
            let user_id = resolve_user_identifier(&state.db_pool, user_identifier)
                .await
                .map_err(|e| {
                    (
                        e.status,
                        Json(ProjectErrorResponse {
                            error: e.message,
                            suggestions: None,
                        }),
                    )
                })?;

            crate::db::project_app_users::add_user(&mut *tx, updated_project.id, user_id)
                .await
                .map_err(|e| {
                    (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        Json(ProjectErrorResponse {
                            error: format!("Failed to add app user: {}", e),
                            suggestions: None,
                        }),
                    )
                })?;
        }

        tx.commit().await.map_err(|e| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ProjectErrorResponse {
                    error: format!("Failed to commit transaction: {}", e),
                    suggestions: None,
                }),
            )
        })?;
    }

    // Update app teams if provided
    if let Some(app_teams) = payload.app_teams {
        let mut tx = state.db_pool.begin().await.map_err(|e| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ProjectErrorResponse {
                    error: format!("Failed to start transaction: {}", e),
                    suggestions: None,
                }),
            )
        })?;

        // Remove all existing app teams
        let existing_teams = crate::db::project_app_users::list_teams(&mut *tx, updated_project.id)
            .await
            .map_err(|e| {
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(ProjectErrorResponse {
                        error: format!("Failed to list existing app teams: {}", e),
                        suggestions: None,
                    }),
                )
            })?;

        for team_id in existing_teams {
            crate::db::project_app_users::remove_team(&mut *tx, updated_project.id, team_id)
                .await
                .map_err(|e| {
                    (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        Json(ProjectErrorResponse {
                            error: format!("Failed to remove app team: {}", e),
                            suggestions: None,
                        }),
                    )
                })?;
        }

        // Add new app teams
        for team_identifier in &app_teams {
            let team_id = resolve_team_identifier(&state.db_pool, team_identifier)
                .await
                .map_err(|e| {
                    (
                        e.status,
                        Json(ProjectErrorResponse {
                            error: e.message,
                            suggestions: None,
                        }),
                    )
                })?;

            crate::db::project_app_users::add_team(&mut *tx, updated_project.id, team_id)
                .await
                .map_err(|e| {
                    (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        Json(ProjectErrorResponse {
                            error: format!("Failed to add app team: {}", e),
                            suggestions: None,
                        }),
                    )
                })?;
        }

        tx.commit().await.map_err(|e| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ProjectErrorResponse {
                    error: format!("Failed to commit transaction: {}", e),
                    suggestions: None,
                }),
            )
        })?;
    }

    // Update status if provided
    if let Some(status) = payload.status {
        updated_project = projects::update_status(
            &state.db_pool,
            updated_project.id,
            crate::db::models::ProjectStatus::from(status),
        )
        .await
        .map_err(|e| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ProjectErrorResponse {
                    error: format!("Failed to update project status: {}", e),
                    suggestions: None,
                }),
            )
        })?;
    }

    let owner_info = resolve_owner_info(&state, &updated_project)
        .await
        .map_err(|e| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ProjectErrorResponse {
                    error: format!("Failed to resolve owner info: {}", e),
                    suggestions: None,
                }),
            )
        })?;

    Ok(Json(UpdateProjectResponse {
        project: convert_project(updated_project, owner_info),
    }))
}

pub async fn delete_project(
    State(state): State<AppState>,
    Extension(user): Extension<User>,
    Path(id_or_name): Path<String>,
    Query(params): Query<GetProjectParams>,
) -> Result<StatusCode, (StatusCode, Json<ProjectErrorResponse>)> {
    // Resolve project by ID or name
    let project = resolve_project(&state, &id_or_name, params.by_id).await?;

    // Check write permission
    let can_write = check_write_permission(&state, &project, &user)
        .await
        .map_err(|e| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ProjectErrorResponse {
                    error: format!("Failed to check permissions: {}", e),
                    suggestions: None,
                }),
            )
        })?;

    if !can_write {
        return Err((
            StatusCode::FORBIDDEN,
            Json(ProjectErrorResponse {
                error: "You do not have permission to delete this project".to_string(),
                suggestions: None,
            }),
        ));
    }

    // Service accounts cannot delete projects
    let is_sa = service_accounts::is_service_account(&state.db_pool, user.id)
        .await
        .map_err(|e| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ProjectErrorResponse {
                    error: format!("Failed to check service account status: {}", e),
                    suggestions: None,
                }),
            )
        })?;

    if is_sa {
        return Err((
            StatusCode::FORBIDDEN,
            Json(ProjectErrorResponse {
                error: "Service accounts cannot modify projects".to_string(),
                suggestions: None,
            }),
        ));
    }

    // Check if already deleting
    if project.status == crate::db::models::ProjectStatus::Deleting {
        return Ok(StatusCode::ACCEPTED);
    }

    // Mark project as deleting
    projects::mark_deleting(&state.db_pool, project.id)
        .await
        .map_err(|e| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ProjectErrorResponse {
                    error: format!("Failed to mark project for deletion: {}", e),
                    suggestions: None,
                }),
            )
        })?;

    tracing::info!("Project {} marked for deletion", project.name);

    // Return 202 Accepted - deletion is asynchronous
    Ok(StatusCode::ACCEPTED)
}

/// Query project by ID
async fn query_project_by_id(
    state: &AppState,
    project_id: &str,
) -> Result<crate::db::models::Project, String> {
    let uuid = Uuid::parse_str(project_id).map_err(|e| format!("Invalid project ID: {}", e))?;

    projects::find_by_id(&state.db_pool, uuid)
        .await
        .map_err(|e| format!("Project not found: {}", e))?
        .ok_or_else(|| "Project not found".to_string())
}

/// Query project by name
async fn query_project_by_name(
    state: &AppState,
    project_name: &str,
) -> Result<crate::db::models::Project, String> {
    tracing::info!("Querying project by name: {}", project_name);

    projects::find_by_name(&state.db_pool, project_name)
        .await
        .map_err(|e| format!("Failed to query project by name: {}", e))?
        .ok_or_else(|| format!("Project '{}' not found", project_name))
}

/// Resolve owner information for a project
async fn resolve_owner_info(
    state: &AppState,
    project: &crate::db::models::Project,
) -> Result<Option<OwnerInfo>, String> {
    if let Some(user_id) = project.owner_user_id {
        let user = db_users::find_by_id(&state.db_pool, user_id)
            .await
            .map_err(|e| format!("Failed to fetch user: {}", e))?
            .ok_or_else(|| "Owner user not found".to_string())?;

        Ok(Some(OwnerInfo::User(UserInfo {
            id: user.id.to_string(),
            email: user.email,
        })))
    } else if let Some(team_id) = project.owner_team_id {
        let team = db_teams::find_by_id(&state.db_pool, team_id)
            .await
            .map_err(|e| format!("Failed to fetch team: {}", e))?
            .ok_or_else(|| "Owner team not found".to_string())?;

        Ok(Some(OwnerInfo::Team(TeamInfo {
            id: team.id.to_string(),
            name: team.name,
        })))
    } else {
        Ok(None)
    }
}

/// Resolve project by ID or name with fuzzy matching support
async fn resolve_project(
    state: &AppState,
    id_or_name: &str,
    by_id: bool,
) -> Result<crate::db::models::Project, (StatusCode, Json<ProjectErrorResponse>)> {
    tracing::info!("Resolving project '{}', by_id={}", id_or_name, by_id);

    let project = if by_id {
        // Explicit ID lookup
        tracing::info!("Using explicit ID lookup");
        query_project_by_id(state, id_or_name).await.map_err(|e| {
            (
                StatusCode::NOT_FOUND,
                Json(ProjectErrorResponse {
                    error: e,
                    suggestions: None,
                }),
            )
        })?
    } else {
        // Try name first, fallback to ID
        tracing::info!("Trying name lookup first, will fallback to ID");
        match query_project_by_name(state, id_or_name).await {
            Ok(project) => project,
            Err(e) => {
                tracing::info!("Name lookup failed: {}, trying ID fallback", e);
                query_project_by_id(state, id_or_name).await.map_err(|_e| {
                    tracing::info!("Both lookups failed, generating fuzzy suggestions");
                    // Both failed - provide fuzzy suggestions
                    let all_projects = tokio::task::block_in_place(|| {
                        tokio::runtime::Handle::current()
                            .block_on(projects::list(&state.db_pool, None))
                    });

                    let suggestions = match all_projects {
                        Ok(all_projects) => {
                            let api_projects: Vec<ApiProject> = all_projects
                                .into_iter()
                                .map(|p| convert_project(p, None))
                                .collect();
                            let similar = find_similar_projects(id_or_name, &api_projects, 0.85);
                            if similar.is_empty() {
                                None
                            } else {
                                Some(similar)
                            }
                        }
                        Err(_) => None,
                    };

                    (
                        StatusCode::NOT_FOUND,
                        Json(ProjectErrorResponse {
                            error: format!("Project '{}' not found", id_or_name),
                            suggestions,
                        }),
                    )
                })?
            }
        }
    };

    Ok(project)
}

/// Load app users and teams for a project
async fn load_app_users_for_project(
    state: &AppState,
    project_id: uuid::Uuid,
) -> Result<(Vec<UserInfo>, Vec<TeamInfo>), String> {
    // Get app user IDs
    let user_ids = crate::db::project_app_users::list_users(&state.db_pool, project_id)
        .await
        .map_err(|e| format!("Failed to list app users: {}", e))?;

    // Get app team IDs
    let team_ids = crate::db::project_app_users::list_teams(&state.db_pool, project_id)
        .await
        .map_err(|e| format!("Failed to list app teams: {}", e))?;

    // Batch fetch user details (if any)
    let users = if !user_ids.is_empty() {
        let users_map = db_users::get_users_batch(&state.db_pool, &user_ids)
            .await
            .map_err(|e| format!("Failed to batch fetch users: {}", e))?;

        user_ids
            .into_iter()
            .filter_map(|id| {
                users_map.get(&id).map(|u| UserInfo {
                    id: u.id.to_string(),
                    email: u.email.clone(),
                })
            })
            .collect()
    } else {
        Vec::new()
    };

    // Batch fetch team details (if any)
    let teams = if !team_ids.is_empty() {
        let teams_map = db_teams::get_teams_batch(&state.db_pool, &team_ids)
            .await
            .map_err(|e| format!("Failed to batch fetch teams: {}", e))?;

        team_ids
            .into_iter()
            .filter_map(|id| {
                teams_map.get(&id).map(|t| TeamInfo {
                    id: t.id.to_string(),
                    name: t.name.clone(),
                })
            })
            .collect()
    } else {
        Vec::new()
    };

    Ok((users, teams))
}

/// Convert database Project model to API Project model
fn convert_project(project: crate::db::models::Project, owner: Option<OwnerInfo>) -> ApiProject {
    ApiProject {
        id: project.id.to_string(),
        created: project.created_at.to_rfc3339(),
        updated: project.updated_at.to_rfc3339(),
        name: project.name,
        status: ProjectStatus::from(project.status),
        access_class: project.access_class,
        owner,
        active_deployment_status: None, // Will be populated by caller if needed
        default_url: None,              // Will be populated by caller
        primary_url: None,              // Will be populated by caller
        custom_domain_urls: vec![],     // Will be populated by caller
        deployment_groups: None,        // Will be populated by caller if needed
        finalizers: project.finalizers.clone(),
        app_users: vec![], // Will be populated by caller if needed
        app_teams: vec![], // Will be populated by caller if needed
    }
}

/// Check if user can read a project (owner, team member, or admin)
pub async fn check_read_permission(
    state: &AppState,
    project: &crate::db::models::Project,
    user: &User,
) -> Result<bool, String> {
    // Admins have full access
    if state.is_admin(&user.email) {
        return Ok(true);
    }

    // Check ownership or team membership
    projects::user_can_access(&state.db_pool, project.id, user.id)
        .await
        .map_err(|e| format!("Failed to check access: {}", e))
}

/// Check if user can write to a project (owner, team member, or admin)
pub async fn check_write_permission(
    state: &AppState,
    project: &crate::db::models::Project,
    user: &User,
) -> Result<bool, String> {
    // Admins have full access
    if state.is_admin(&user.email) {
        return Ok(true);
    }

    // Write access requires ownership (user or team member)
    projects::user_can_access(&state.db_pool, project.id, user.id)
        .await
        .map_err(|e| format!("Failed to check access: {}", e))
}