mockforge-collab 0.3.123

Cloud collaboration features for MockForge - team workspaces, real-time sync, and version control
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
//! REST API endpoints for collaboration

use crate::auth::{AuthService, Credentials};
use crate::backup::{BackupService, StorageBackend};
use crate::error::{CollabError, Result};
use crate::history::VersionControl;
use crate::merge::MergeService;
use crate::middleware::{auth_middleware, AuthUser};
use crate::models::UserRole;
use crate::sync::SyncEngine;
use crate::user::UserService;
use crate::workspace::WorkspaceService;
use axum::{
    extract::{Path, Query, State},
    http::StatusCode,
    middleware,
    response::{IntoResponse, Response},
    routing::{delete, get, post, put},
    Extension, Json, Router,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use uuid::Uuid;

/// API state
#[derive(Clone)]
pub struct ApiState {
    /// Authentication service
    pub auth: Arc<AuthService>,
    /// User service
    pub user: Arc<UserService>,
    /// Workspace service
    pub workspace: Arc<WorkspaceService>,
    /// Version control history
    pub history: Arc<VersionControl>,
    /// Merge service
    pub merge: Arc<MergeService>,
    /// Backup service
    pub backup: Arc<BackupService>,
    /// Sync engine
    pub sync: Arc<SyncEngine>,
}

/// Create API router
pub fn create_router(state: ApiState) -> Router {
    // Public routes (no authentication required)
    let public_routes = Router::new()
        .route("/auth/register", post(register))
        .route("/auth/login", post(login))
        .route("/health", get(health_check))
        .route("/ready", get(readiness_check));

    // Protected routes (authentication required)
    let protected_routes = Router::new()
        // Workspaces
        .route("/workspaces", post(create_workspace))
        .route("/workspaces", get(list_workspaces))
        .route("/workspaces/{id}", get(get_workspace))
        .route("/workspaces/{id}", put(update_workspace))
        .route("/workspaces/{id}", delete(delete_workspace))
        // Members
        .route("/workspaces/{id}/members", post(add_member))
        .route("/workspaces/{id}/members/{user_id}", delete(remove_member))
        .route("/workspaces/{id}/members/{user_id}/role", put(change_role))
        .route("/workspaces/{id}/members", get(list_members))
        // Version Control - Commits
        .route("/workspaces/{id}/commits", post(create_commit))
        .route("/workspaces/{id}/commits", get(list_commits))
        .route("/workspaces/{id}/commits/{commit_id}", get(get_commit))
        .route("/workspaces/{id}/restore/{commit_id}", post(restore_to_commit))
        // Version Control - Snapshots
        .route("/workspaces/{id}/snapshots", post(create_snapshot))
        .route("/workspaces/{id}/snapshots", get(list_snapshots))
        .route("/workspaces/{id}/snapshots/{name}", get(get_snapshot))
        // Fork and Merge
        .route("/workspaces/{id}/fork", post(fork_workspace))
        .route("/workspaces/{id}/forks", get(list_forks))
        .route("/workspaces/{id}/merge", post(merge_workspaces))
        .route("/workspaces/{id}/merges", get(list_merges))
        // Backup and Restore
        .route("/workspaces/{id}/backup", post(create_backup))
        .route("/workspaces/{id}/backups", get(list_backups))
        .route("/workspaces/{id}/backups/{backup_id}", delete(delete_backup))
        .route("/workspaces/{id}/restore", post(restore_workspace))
        // State Management
        .route("/workspaces/{id}/state", get(get_workspace_state))
        .route("/workspaces/{id}/state", post(update_workspace_state))
        .route("/workspaces/{id}/state/history", get(get_state_history))
        .route_layer(middleware::from_fn_with_state(
            state.auth.clone(),
            auth_middleware,
        ));

    // Combine routes
    Router::new().merge(public_routes).merge(protected_routes).with_state(state)
}

// ===== Request/Response Types =====

/// User registration request
#[derive(Debug, Deserialize)]
pub struct RegisterRequest {
    /// Username for the new account
    pub username: String,
    /// Email address
    pub email: String,
    /// Password
    pub password: String,
}

/// Authentication response with JWT token
#[derive(Debug, Serialize)]
pub struct AuthResponse {
    /// JWT access token
    pub access_token: String,
    /// Token type (Bearer)
    pub token_type: String,
    /// Token expiration timestamp
    pub expires_at: String,
}

/// Request to create a new workspace
#[derive(Debug, Deserialize)]
pub struct CreateWorkspaceRequest {
    /// Workspace name
    pub name: String,
    /// Optional description
    pub description: Option<String>,
}

/// Request to update workspace settings
#[derive(Debug, Deserialize)]
pub struct UpdateWorkspaceRequest {
    /// New workspace name
    pub name: Option<String>,
    /// New description
    pub description: Option<String>,
}

/// Request to add a member to a workspace
#[derive(Debug, Deserialize)]
pub struct AddMemberRequest {
    /// User ID to add
    pub user_id: Uuid,
    /// Role to assign
    pub role: UserRole,
}

/// Request to change a member's role
#[derive(Debug, Deserialize)]
pub struct ChangeRoleRequest {
    /// New role to assign
    pub role: UserRole,
}

/// Request to create a new commit
#[derive(Debug, Deserialize)]
pub struct CreateCommitRequest {
    /// Commit message
    pub message: String,
    /// Changes description as JSON
    pub changes: serde_json::Value,
}

/// Request to create a named snapshot
#[derive(Debug, Deserialize)]
pub struct CreateSnapshotRequest {
    /// Snapshot name
    pub name: String,
    /// Optional description
    pub description: Option<String>,
    /// Commit ID to snapshot
    pub commit_id: Uuid,
}

/// Pagination query parameters
#[derive(Debug, Deserialize)]
pub struct PaginationQuery {
    /// Number of items to return
    #[serde(default = "default_limit")]
    pub limit: i32,
    /// Number of items to skip
    #[serde(default)]
    pub offset: i32,
}

const fn default_limit() -> i32 {
    50
}

// ===== Error Handling =====

impl IntoResponse for CollabError {
    fn into_response(self) -> Response {
        let (status, message) = match &self {
            Self::AuthenticationFailed(msg) => (StatusCode::UNAUTHORIZED, msg.clone()),
            Self::AuthorizationFailed(msg) => (StatusCode::FORBIDDEN, msg.clone()),
            Self::WorkspaceNotFound(msg) | Self::UserNotFound(msg) => {
                (StatusCode::NOT_FOUND, msg.clone())
            }
            Self::InvalidInput(msg) => (StatusCode::BAD_REQUEST, msg.clone()),
            Self::AlreadyExists(msg) | Self::ConflictDetected(msg) => {
                (StatusCode::CONFLICT, msg.clone())
            }
            Self::Timeout(msg) => (StatusCode::REQUEST_TIMEOUT, msg.clone()),
            Self::Internal(msg)
            | Self::DatabaseError(msg)
            | Self::SerializationError(msg)
            | Self::SyncError(msg)
            | Self::WebSocketError(msg)
            | Self::ConnectionError(msg) => (StatusCode::INTERNAL_SERVER_ERROR, msg.clone()),
            Self::VersionMismatch { expected, actual } => (
                StatusCode::CONFLICT,
                format!("Version mismatch: expected {expected}, got {actual}"),
            ),
        };

        (status, Json(serde_json::json!({ "error": message }))).into_response()
    }
}

// ===== Handler Functions =====

/// Register a new user
async fn register(
    State(state): State<ApiState>,
    Json(payload): Json<RegisterRequest>,
) -> Result<Json<AuthResponse>> {
    // Create user
    let user = state
        .user
        .create_user(payload.username, payload.email, payload.password)
        .await?;

    // Generate token
    let token = state.auth.generate_token(&user)?;

    Ok(Json(AuthResponse {
        access_token: token.access_token,
        token_type: token.token_type,
        expires_at: token.expires_at.to_rfc3339(),
    }))
}

/// Login user
async fn login(
    State(state): State<ApiState>,
    Json(payload): Json<Credentials>,
) -> Result<Json<AuthResponse>> {
    // Authenticate user
    let user = state.user.authenticate(&payload.username, &payload.password).await?;

    // Generate token
    let token = state.auth.generate_token(&user)?;

    Ok(Json(AuthResponse {
        access_token: token.access_token,
        token_type: token.token_type,
        expires_at: token.expires_at.to_rfc3339(),
    }))
}

/// Create a new workspace
async fn create_workspace(
    State(state): State<ApiState>,
    Extension(auth_user): Extension<AuthUser>,
    Json(payload): Json<CreateWorkspaceRequest>,
) -> Result<Json<serde_json::Value>> {
    // Create workspace
    let workspace = state
        .workspace
        .create_workspace(payload.name, payload.description, auth_user.user_id)
        .await?;

    Ok(Json(serde_json::to_value(workspace)?))
}

/// List user's workspaces
async fn list_workspaces(
    State(state): State<ApiState>,
    Extension(auth_user): Extension<AuthUser>,
) -> Result<Json<serde_json::Value>> {
    // List workspaces
    let workspaces = state.workspace.list_user_workspaces(auth_user.user_id).await?;

    Ok(Json(serde_json::to_value(workspaces)?))
}

/// Get workspace by ID
async fn get_workspace(
    State(state): State<ApiState>,
    Path(id): Path<Uuid>,
    Extension(auth_user): Extension<AuthUser>,
) -> Result<Json<serde_json::Value>> {
    // Verify user is a member
    let _member = state.workspace.get_member(id, auth_user.user_id).await?;

    // Get workspace
    let workspace = state.workspace.get_workspace(id).await?;

    Ok(Json(serde_json::to_value(workspace)?))
}

/// Update workspace
async fn update_workspace(
    State(state): State<ApiState>,
    Path(id): Path<Uuid>,
    Extension(auth_user): Extension<AuthUser>,
    Json(payload): Json<UpdateWorkspaceRequest>,
) -> Result<Json<serde_json::Value>> {
    // Update workspace (permission check inside)
    let workspace = state
        .workspace
        .update_workspace(id, auth_user.user_id, payload.name, payload.description, None)
        .await?;

    Ok(Json(serde_json::to_value(workspace)?))
}

/// Delete workspace
async fn delete_workspace(
    State(state): State<ApiState>,
    Path(id): Path<Uuid>,
    Extension(auth_user): Extension<AuthUser>,
) -> Result<StatusCode> {
    // Delete workspace (permission check inside)
    state.workspace.delete_workspace(id, auth_user.user_id).await?;

    Ok(StatusCode::NO_CONTENT)
}

/// Add member to workspace
async fn add_member(
    State(state): State<ApiState>,
    Path(workspace_id): Path<Uuid>,
    Extension(auth_user): Extension<AuthUser>,
    Json(payload): Json<AddMemberRequest>,
) -> Result<Json<serde_json::Value>> {
    // Add member (permission check inside)
    let member = state
        .workspace
        .add_member(workspace_id, auth_user.user_id, payload.user_id, payload.role)
        .await?;

    Ok(Json(serde_json::to_value(member)?))
}

/// Remove member from workspace
async fn remove_member(
    State(state): State<ApiState>,
    Path((workspace_id, member_user_id)): Path<(Uuid, Uuid)>,
    Extension(auth_user): Extension<AuthUser>,
) -> Result<StatusCode> {
    // Remove member (permission check inside)
    state
        .workspace
        .remove_member(workspace_id, auth_user.user_id, member_user_id)
        .await?;

    Ok(StatusCode::NO_CONTENT)
}

/// Change member role
async fn change_role(
    State(state): State<ApiState>,
    Path((workspace_id, member_user_id)): Path<(Uuid, Uuid)>,
    Extension(auth_user): Extension<AuthUser>,
    Json(payload): Json<ChangeRoleRequest>,
) -> Result<Json<serde_json::Value>> {
    // Change role (permission check inside)
    let member = state
        .workspace
        .change_role(workspace_id, auth_user.user_id, member_user_id, payload.role)
        .await?;

    Ok(Json(serde_json::to_value(member)?))
}

/// List workspace members
async fn list_members(
    State(state): State<ApiState>,
    Path(workspace_id): Path<Uuid>,
    Extension(auth_user): Extension<AuthUser>,
) -> Result<Json<serde_json::Value>> {
    // Verify user is a member
    let _member = state.workspace.get_member(workspace_id, auth_user.user_id).await?;

    // List all members
    let members = state.workspace.list_members(workspace_id).await?;

    Ok(Json(serde_json::to_value(members)?))
}

/// Health check endpoint
async fn health_check() -> impl IntoResponse {
    Json(serde_json::json!({
        "status": "healthy",
        "timestamp": chrono::Utc::now().to_rfc3339(),
    }))
}

/// Readiness check endpoint with database health check
async fn readiness_check(State(state): State<ApiState>) -> impl IntoResponse {
    // Check database connection by running a simple query
    // We need to access the database pool - let's add it to ApiState or use workspace service
    // For now, we'll use a workspace service method to check DB health
    let db_healthy = state.workspace.check_database_health().await;

    if db_healthy {
        Json(serde_json::json!({
            "status": "ready",
            "database": "healthy",
            "timestamp": chrono::Utc::now().to_rfc3339(),
        }))
        .into_response()
    } else {
        (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(serde_json::json!({
                "status": "not_ready",
                "database": "unhealthy",
                "timestamp": chrono::Utc::now().to_rfc3339(),
            })),
        )
            .into_response()
    }
}

// ===== Validation Helpers =====

/// Validate commit message
fn validate_commit_message(message: &str) -> Result<()> {
    if message.is_empty() {
        return Err(CollabError::InvalidInput("Commit message cannot be empty".to_string()));
    }
    if message.len() > 500 {
        return Err(CollabError::InvalidInput(
            "Commit message cannot exceed 500 characters".to_string(),
        ));
    }
    Ok(())
}

/// Validate snapshot name
fn validate_snapshot_name(name: &str) -> Result<()> {
    if name.is_empty() {
        return Err(CollabError::InvalidInput("Snapshot name cannot be empty".to_string()));
    }
    if name.len() > 100 {
        return Err(CollabError::InvalidInput(
            "Snapshot name cannot exceed 100 characters".to_string(),
        ));
    }
    // Allow alphanumeric, hyphens, underscores, and dots
    if !name.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '.') {
        return Err(CollabError::InvalidInput(
            "Snapshot name can only contain alphanumeric characters, hyphens, underscores, and dots".to_string(),
        ));
    }
    Ok(())
}

// ===== Version Control Handlers =====

/// Create a commit in the workspace.
///
/// Creates a new commit capturing the current state of the workspace along with
/// a description of changes. This is similar to `git commit`.
///
/// # Requirements
/// - User must be a workspace member with Editor or Admin role
/// - Commit message must be 1-500 characters
///
/// # Request Body
/// - `message`: Commit message describing the changes (required, 1-500 chars)
/// - `changes`: JSON object describing what changed
///
/// # Response
/// Returns the created Commit object with:
/// - `id`: Unique commit ID
/// - `workspace_id`: ID of the workspace
/// - `author_id`: ID of the user who created the commit
/// - `message`: Commit message
/// - `parent_id`: ID of the parent commit (null for first commit)
/// - `version`: Version number (auto-incremented)
/// - `snapshot`: Full workspace state at this commit
/// - `changes`: Description of what changed
/// - `created_at`: Timestamp
///
/// # Errors
/// - `401 Unauthorized`: Not authenticated
/// - `403 Forbidden`: User is not Editor or Admin
/// - `404 Not Found`: Workspace not found or user not a member
/// - `400 Bad Request`: Invalid commit message
async fn create_commit(
    State(state): State<ApiState>,
    Path(workspace_id): Path<Uuid>,
    Extension(auth_user): Extension<AuthUser>,
    Json(payload): Json<CreateCommitRequest>,
) -> Result<Json<serde_json::Value>> {
    // Validate input
    validate_commit_message(&payload.message)?;

    // Verify user has permission (Editor or Admin)
    let member = state.workspace.get_member(workspace_id, auth_user.user_id).await?;
    if !matches!(member.role, UserRole::Admin | UserRole::Editor) {
        return Err(CollabError::AuthorizationFailed(
            "Only Admins and Editors can create commits".to_string(),
        ));
    }

    // Get current workspace state
    let workspace = state.workspace.get_workspace(workspace_id).await?;

    // Get parent commit (latest)
    let parent = state.history.get_latest_commit(workspace_id).await?;
    let parent_id = parent.as_ref().map(|c| c.id);
    let version = parent.as_ref().map_or(1, |c| c.version + 1);

    // Create snapshot of current state
    let snapshot = serde_json::to_value(&workspace)?;

    // Create commit
    let commit = state
        .history
        .create_commit(
            workspace_id,
            auth_user.user_id,
            payload.message,
            parent_id,
            version,
            snapshot,
            payload.changes,
        )
        .await?;

    Ok(Json(serde_json::to_value(commit)?))
}

/// List commits for a workspace.
///
/// Returns the commit history for a workspace in reverse chronological order
/// (most recent first). Supports pagination via query parameters.
///
/// # Requirements
/// - User must be a workspace member (any role)
///
/// # Query Parameters
/// - `limit`: Number of commits to return (default: 50, max: 100)
/// - `offset`: Number of commits to skip (default: 0)
///
/// # Response
/// Returns a JSON object with:
/// - `commits`: Array of Commit objects
/// - `pagination`: Object with `limit` and `offset` values
///
/// # Example
/// ```text
/// GET /workspaces/{id}/commits?limit=20&offset=0
/// ```
///
/// # Errors
/// - `401 Unauthorized`: Not authenticated
/// - `404 Not Found`: Workspace not found or user not a member
async fn list_commits(
    State(state): State<ApiState>,
    Path(workspace_id): Path<Uuid>,
    Extension(auth_user): Extension<AuthUser>,
    Query(pagination): Query<PaginationQuery>,
) -> Result<Json<serde_json::Value>> {
    // Verify user is a member
    let _member = state.workspace.get_member(workspace_id, auth_user.user_id).await?;

    // Validate pagination params
    let limit = pagination.limit.clamp(1, 100);

    // Get commit history
    let commits = state.history.get_history(workspace_id, Some(limit)).await?;

    // Return with pagination metadata
    Ok(Json(serde_json::json!({
        "commits": commits,
        "pagination": {
            "limit": limit,
            "offset": pagination.offset,
        }
    })))
}

/// Get a specific commit by ID.
///
/// Retrieves detailed information about a specific commit, including the full
/// workspace state snapshot at that point in time.
///
/// # Requirements
/// - User must be a workspace member (any role)
/// - Commit must belong to the specified workspace
///
/// # Errors
/// - `401 Unauthorized`: Not authenticated
/// - `404 Not Found`: Commit or workspace not found
/// - `400 Bad Request`: Commit doesn't belong to this workspace
async fn get_commit(
    State(state): State<ApiState>,
    Path((workspace_id, commit_id)): Path<(Uuid, Uuid)>,
    Extension(auth_user): Extension<AuthUser>,
) -> Result<Json<serde_json::Value>> {
    // Verify user is a member
    let _member = state.workspace.get_member(workspace_id, auth_user.user_id).await?;

    // Get commit
    let commit = state.history.get_commit(commit_id).await?;

    // Verify commit belongs to this workspace
    if commit.workspace_id != workspace_id {
        return Err(CollabError::InvalidInput(
            "Commit does not belong to this workspace".to_string(),
        ));
    }

    Ok(Json(serde_json::to_value(commit)?))
}

/// Restore workspace to a specific commit.
///
/// Reverts the workspace to the state captured in the specified commit.
/// This is a destructive operation that should be used carefully.
///
/// # Requirements
/// - User must be a workspace member with Editor or Admin role
/// - Commit must exist and belong to the workspace
///
/// # Response
/// Returns an object with:
/// - `workspace_id`: ID of the restored workspace
/// - `commit_id`: ID of the commit that was restored
/// - `restored_state`: The workspace state from the commit
///
/// # Errors
/// - `401 Unauthorized`: Not authenticated
/// - `403 Forbidden`: User is not Editor or Admin
/// - `404 Not Found`: Commit or workspace not found
async fn restore_to_commit(
    State(state): State<ApiState>,
    Path((workspace_id, commit_id)): Path<(Uuid, Uuid)>,
    Extension(auth_user): Extension<AuthUser>,
) -> Result<Json<serde_json::Value>> {
    // Verify user has permission (Editor or Admin)
    let member = state.workspace.get_member(workspace_id, auth_user.user_id).await?;
    if !matches!(member.role, UserRole::Admin | UserRole::Editor) {
        return Err(CollabError::AuthorizationFailed(
            "Only Admins and Editors can restore workspaces".to_string(),
        ));
    }

    // Restore to commit
    let restored_state = state.history.restore_to_commit(workspace_id, commit_id).await?;

    Ok(Json(serde_json::json!({
        "workspace_id": workspace_id,
        "commit_id": commit_id,
        "restored_state": restored_state
    })))
}

/// Create a named snapshot.
///
/// Creates a named reference to a specific commit, similar to a git tag.
/// Snapshots are useful for marking important states like releases.
///
/// # Requirements
/// - User must be a workspace member with Editor or Admin role
/// - Snapshot name must be 1-100 characters, alphanumeric with -, _, or .
/// - Commit must exist
///
/// # Request Body
/// - `name`: Name for the snapshot (required, 1-100 chars, alphanumeric)
/// - `description`: Optional description
/// - `commit_id`: ID of the commit to snapshot
///
/// # Errors
/// - `401 Unauthorized`: Not authenticated
/// - `403 Forbidden`: User is not Editor or Admin
/// - `404 Not Found`: Workspace or commit not found
/// - `400 Bad Request`: Invalid snapshot name
async fn create_snapshot(
    State(state): State<ApiState>,
    Path(workspace_id): Path<Uuid>,
    Extension(auth_user): Extension<AuthUser>,
    Json(payload): Json<CreateSnapshotRequest>,
) -> Result<Json<serde_json::Value>> {
    // Validate input
    validate_snapshot_name(&payload.name)?;

    // Verify user has permission (Editor or Admin)
    let member = state.workspace.get_member(workspace_id, auth_user.user_id).await?;
    if !matches!(member.role, UserRole::Admin | UserRole::Editor) {
        return Err(CollabError::AuthorizationFailed(
            "Only Admins and Editors can create snapshots".to_string(),
        ));
    }

    // Create snapshot
    let snapshot = state
        .history
        .create_snapshot(
            workspace_id,
            payload.name,
            payload.description,
            payload.commit_id,
            auth_user.user_id,
        )
        .await?;

    Ok(Json(serde_json::to_value(snapshot)?))
}

/// List snapshots for a workspace.
///
/// Returns all named snapshots for the workspace in reverse chronological order.
///
/// # Requirements
/// - User must be a workspace member (any role)
///
/// # Errors
/// - `401 Unauthorized`: Not authenticated
/// - `404 Not Found`: Workspace not found or user not a member
async fn list_snapshots(
    State(state): State<ApiState>,
    Path(workspace_id): Path<Uuid>,
    Extension(auth_user): Extension<AuthUser>,
) -> Result<Json<serde_json::Value>> {
    // Verify user is a member
    let _member = state.workspace.get_member(workspace_id, auth_user.user_id).await?;

    // List snapshots
    let snapshots = state.history.list_snapshots(workspace_id).await?;

    Ok(Json(serde_json::to_value(snapshots)?))
}

/// Get a specific snapshot by name.
///
/// Retrieves details about a named snapshot, including which commit it references.
///
/// # Requirements
/// - User must be a workspace member (any role)
///
/// # Errors
/// - `401 Unauthorized`: Not authenticated
/// - `404 Not Found`: Snapshot, workspace not found, or user not a member
async fn get_snapshot(
    State(state): State<ApiState>,
    Path((workspace_id, name)): Path<(Uuid, String)>,
    Extension(auth_user): Extension<AuthUser>,
) -> Result<Json<serde_json::Value>> {
    // Verify user is a member
    let _member = state.workspace.get_member(workspace_id, auth_user.user_id).await?;

    // Get snapshot
    let snapshot = state.history.get_snapshot(workspace_id, &name).await?;

    Ok(Json(serde_json::to_value(snapshot)?))
}

// ===== Fork and Merge Handlers =====

/// Request to fork a workspace
#[derive(Debug, Deserialize)]
pub struct ForkWorkspaceRequest {
    /// Name for the forked workspace
    #[serde(alias = "new_name")]
    pub name: Option<String>,
    /// Commit ID to fork from
    pub fork_point_commit_id: Option<Uuid>,
}

/// Fork a workspace
async fn fork_workspace(
    State(state): State<ApiState>,
    Path(workspace_id): Path<Uuid>,
    Extension(auth_user): Extension<AuthUser>,
    Json(payload): Json<ForkWorkspaceRequest>,
) -> Result<Json<serde_json::Value>> {
    // Verify user has access to source workspace
    let _member = state.workspace.get_member(workspace_id, auth_user.user_id).await?;

    // Fork workspace
    let forked = state
        .workspace
        .fork_workspace(workspace_id, payload.name, auth_user.user_id, payload.fork_point_commit_id)
        .await?;

    Ok(Json(serde_json::to_value(forked)?))
}

/// List all forks of a workspace
async fn list_forks(
    State(state): State<ApiState>,
    Path(workspace_id): Path<Uuid>,
    Extension(auth_user): Extension<AuthUser>,
) -> Result<Json<serde_json::Value>> {
    // Verify user is a member
    let _member = state.workspace.get_member(workspace_id, auth_user.user_id).await?;

    // List forks
    let forks = state.workspace.list_forks(workspace_id).await?;

    Ok(Json(serde_json::to_value(forks)?))
}

/// Request to merge workspaces
#[derive(Debug, Deserialize)]
pub struct MergeWorkspacesRequest {
    /// Source workspace ID to merge from
    pub source_workspace_id: Uuid,
}

/// Merge changes from another workspace
async fn merge_workspaces(
    State(state): State<ApiState>,
    Path(target_workspace_id): Path<Uuid>,
    Extension(auth_user): Extension<AuthUser>,
    Json(payload): Json<MergeWorkspacesRequest>,
) -> Result<Json<serde_json::Value>> {
    // Verify user has permission to merge into target
    let member = state.workspace.get_member(target_workspace_id, auth_user.user_id).await?;
    if !matches!(member.role, UserRole::Admin | UserRole::Editor) {
        return Err(CollabError::AuthorizationFailed(
            "Only Admins and Editors can merge workspaces".to_string(),
        ));
    }

    // Perform merge
    let (merged_state, conflicts) = state
        .merge
        .merge_workspaces(payload.source_workspace_id, target_workspace_id, auth_user.user_id)
        .await?;

    Ok(Json(serde_json::json!({
        "workspace": merged_state,
        "conflicts": conflicts,
        "has_conflicts": !conflicts.is_empty()
    })))
}

/// List merge operations for a workspace
async fn list_merges(
    State(state): State<ApiState>,
    Path(workspace_id): Path<Uuid>,
    Extension(auth_user): Extension<AuthUser>,
) -> Result<Json<serde_json::Value>> {
    // Verify user is a member
    let _member = state.workspace.get_member(workspace_id, auth_user.user_id).await?;

    // List merges
    let merges = state.merge.list_merges(workspace_id).await?;

    Ok(Json(serde_json::to_value(merges)?))
}

// ===== Backup and Restore Handlers =====

/// Request to create a workspace backup
#[derive(Debug, Deserialize)]
pub struct CreateBackupRequest {
    /// Storage backend type
    pub storage_backend: Option<String>,
    /// Backup format
    pub format: Option<String>,
    /// Commit ID to backup
    pub commit_id: Option<Uuid>,
}

/// Create a backup of a workspace
#[allow(clippy::large_futures)]
async fn create_backup(
    State(state): State<ApiState>,
    Path(workspace_id): Path<Uuid>,
    Extension(auth_user): Extension<AuthUser>,
    Json(payload): Json<CreateBackupRequest>,
) -> Result<Json<serde_json::Value>> {
    // Verify user has permission
    let member = state.workspace.get_member(workspace_id, auth_user.user_id).await?;
    if !matches!(member.role, UserRole::Admin | UserRole::Editor) {
        return Err(CollabError::AuthorizationFailed(
            "Only Admins and Editors can create backups".to_string(),
        ));
    }

    // Determine storage backend
    let storage_backend = match payload.storage_backend.as_deref() {
        Some("s3") => StorageBackend::S3,
        Some("azure") => StorageBackend::Azure,
        Some("gcs") => StorageBackend::Gcs,
        Some("custom") => StorageBackend::Custom,
        _ => StorageBackend::Local,
    };

    // Create backup
    let backup = state
        .backup
        .backup_workspace(
            workspace_id,
            auth_user.user_id,
            storage_backend,
            payload.format,
            payload.commit_id,
        )
        .await?;

    Ok(Json(serde_json::to_value(backup)?))
}

/// List backups for a workspace
async fn list_backups(
    State(state): State<ApiState>,
    Path(workspace_id): Path<Uuid>,
    Extension(auth_user): Extension<AuthUser>,
    Query(pagination): Query<PaginationQuery>,
) -> Result<Json<serde_json::Value>> {
    // Verify user is a member
    let _member = state.workspace.get_member(workspace_id, auth_user.user_id).await?;

    // List backups
    let backups = state.backup.list_backups(workspace_id, Some(pagination.limit)).await?;

    Ok(Json(serde_json::to_value(backups)?))
}

/// Delete a backup
async fn delete_backup(
    State(state): State<ApiState>,
    Path((workspace_id, backup_id)): Path<(Uuid, Uuid)>,
    Extension(auth_user): Extension<AuthUser>,
) -> Result<StatusCode> {
    // Verify user has permission
    let member = state.workspace.get_member(workspace_id, auth_user.user_id).await?;
    if !matches!(member.role, UserRole::Admin) {
        return Err(CollabError::AuthorizationFailed("Only Admins can delete backups".to_string()));
    }

    // Delete backup
    state.backup.delete_backup(backup_id).await?;

    Ok(StatusCode::NO_CONTENT)
}

/// Request to restore a workspace from a backup
#[derive(Debug, Deserialize)]
pub struct RestoreWorkspaceRequest {
    /// Backup ID to restore from
    pub backup_id: Uuid,
    /// Target workspace ID (creates new if None)
    pub target_workspace_id: Option<Uuid>,
}

/// Restore a workspace from a backup
async fn restore_workspace(
    State(state): State<ApiState>,
    Path(workspace_id): Path<Uuid>,
    Extension(auth_user): Extension<AuthUser>,
    Json(payload): Json<RestoreWorkspaceRequest>,
) -> Result<Json<serde_json::Value>> {
    // Verify user has permission
    let member = state.workspace.get_member(workspace_id, auth_user.user_id).await?;
    if !matches!(member.role, UserRole::Admin) {
        return Err(CollabError::AuthorizationFailed(
            "Only Admins can restore workspaces".to_string(),
        ));
    }

    // Restore workspace
    let restored_id = state
        .backup
        .restore_workspace(payload.backup_id, payload.target_workspace_id, auth_user.user_id)
        .await?;

    Ok(Json(serde_json::json!({
        "workspace_id": restored_id,
        "restored_from_backup": payload.backup_id
    })))
}

// ===== State Management Handlers =====

/// Get current workspace state
async fn get_workspace_state(
    State(state): State<ApiState>,
    Path(workspace_id): Path<Uuid>,
    Extension(auth_user): Extension<AuthUser>,
    Query(params): Query<std::collections::HashMap<String, String>>,
) -> Result<Json<serde_json::Value>> {
    // Verify user is a member
    let _member = state.workspace.get_member(workspace_id, auth_user.user_id).await?;

    // Get version if specified
    let version = params.get("version").and_then(|v| v.parse::<i64>().ok());

    // Get state from sync engine - try full workspace state first
    let sync_state = if let Some(version) = version {
        state.sync.load_state_snapshot(workspace_id, Some(version)).await?
    } else {
        // Try to get full workspace state using CoreBridge
        if let Ok(Some(full_state)) = state.sync.get_full_workspace_state(workspace_id).await {
            // Get workspace for version info
            let workspace = state.workspace.get_workspace(workspace_id).await?;
            return Ok(Json(serde_json::json!({
                "workspace_id": workspace_id,
                "version": workspace.version,
                "state": full_state,
                "last_updated": workspace.updated_at
            })));
        }

        // Fallback to in-memory state
        state.sync.get_state(workspace_id)
    };

    if let Some(state_val) = sync_state {
        Ok(Json(serde_json::json!({
            "workspace_id": workspace_id,
            "version": state_val.version,
            "state": state_val.state,
            "last_updated": state_val.last_updated
        })))
    } else {
        // Return workspace metadata if no state available
        let workspace = state.workspace.get_workspace(workspace_id).await?;
        Ok(Json(serde_json::json!({
            "workspace_id": workspace_id,
            "version": workspace.version,
            "state": workspace.config,
            "last_updated": workspace.updated_at
        })))
    }
}

/// Request to update workspace state via sync
#[derive(Debug, Deserialize)]
pub struct UpdateWorkspaceStateRequest {
    /// New workspace state as JSON
    pub state: serde_json::Value,
}

/// Update workspace state
async fn update_workspace_state(
    State(state): State<ApiState>,
    Path(workspace_id): Path<Uuid>,
    Extension(auth_user): Extension<AuthUser>,
    Json(payload): Json<UpdateWorkspaceStateRequest>,
) -> Result<Json<serde_json::Value>> {
    // Verify user has permission
    let member = state.workspace.get_member(workspace_id, auth_user.user_id).await?;
    if !matches!(member.role, UserRole::Admin | UserRole::Editor) {
        return Err(CollabError::AuthorizationFailed(
            "Only Admins and Editors can update workspace state".to_string(),
        ));
    }

    // Update state in sync engine
    state.sync.update_state(workspace_id, payload.state.clone())?;

    // Record state change
    let workspace = state.workspace.get_workspace(workspace_id).await?;
    state
        .sync
        .record_state_change(
            workspace_id,
            "full_sync",
            payload.state.clone(),
            workspace.version + 1,
            auth_user.user_id,
        )
        .await?;

    Ok(Json(serde_json::json!({
        "workspace_id": workspace_id,
        "version": workspace.version + 1,
        "state": payload.state
    })))
}

/// Get state change history
async fn get_state_history(
    State(state): State<ApiState>,
    Path(workspace_id): Path<Uuid>,
    Extension(auth_user): Extension<AuthUser>,
    Query(params): Query<std::collections::HashMap<String, String>>,
) -> Result<Json<serde_json::Value>> {
    // Verify user is a member
    let _member = state.workspace.get_member(workspace_id, auth_user.user_id).await?;

    // Get since_version if specified
    let since_version =
        params.get("since_version").and_then(|v| v.parse::<i64>().ok()).unwrap_or(0);

    // Get state changes
    let changes = state.sync.get_state_changes_since(workspace_id, since_version).await?;

    Ok(Json(serde_json::json!({
        "workspace_id": workspace_id,
        "since_version": since_version,
        "changes": changes
    })))
}

#[cfg(test)]
mod tests {
    #[tokio::test]
    async fn test_router_creation() {
        // Just ensure router can be created
        use super::*;
        use crate::core_bridge::CoreBridge;
        use crate::events::EventBus;
        use sqlx::SqlitePool;
        use tempfile::TempDir;

        // Create temporary directory for test workspace and backup
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let workspace_dir = temp_dir.path().join("workspaces");
        let backup_dir = temp_dir.path().join("backups");
        std::fs::create_dir_all(&workspace_dir).expect("Failed to create workspace dir");
        std::fs::create_dir_all(&backup_dir).expect("Failed to create backup dir");

        // Use in-memory database for testing
        let db = SqlitePool::connect("sqlite::memory:")
            .await
            .expect("Failed to create database pool");

        // Run migrations
        sqlx::migrate!("./migrations").run(&db).await.expect("Failed to run migrations");

        // Create CoreBridge
        let core_bridge = Arc::new(CoreBridge::new(&workspace_dir));

        // Create services
        let auth = Arc::new(AuthService::new("test-secret-key".to_string()));
        let user = Arc::new(UserService::new(db.clone(), auth.clone()));
        let workspace =
            Arc::new(WorkspaceService::with_core_bridge(db.clone(), core_bridge.clone()));
        let history = Arc::new(VersionControl::new(db.clone()));
        let merge = Arc::new(MergeService::new(db.clone()));
        let backup = Arc::new(BackupService::new(
            db.clone(),
            Some(backup_dir.to_string_lossy().to_string()),
            core_bridge,
            workspace.clone(),
        ));
        let event_bus = Arc::new(EventBus::new(100));
        let sync = Arc::new(SyncEngine::new(event_bus));

        let state = ApiState {
            auth,
            user,
            workspace,
            history,
            merge,
            backup,
            sync,
        };
        let _router = create_router(state);
    }
}