rusmes-jmap 0.1.2

JMAP server for RusMES — RFC 8620/8621 HTTP/JSON mail API with Email, Mailbox, Thread, Blob, EventSource push, and VacationResponse support
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
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
//! Identity method implementations for JMAP
//!
//! Implements:
//! - Identity/get, Identity/set - sender identities
//! - Identity/changes - identity tracking

use crate::methods::ensure_account_ownership;
use crate::types::{JmapSetError, Principal};
use async_trait::async_trait;
use rusmes_storage::MessageStore;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

/// Persisted state for one account's identities
#[derive(Debug, Clone, Serialize, Deserialize)]
struct IdentityAccountState {
    /// Map of identity id → Identity
    identities: HashMap<String, Identity>,
    /// Monotonic version counter; incremented on every mutation
    state_version: u64,
}

impl IdentityAccountState {
    fn new_with_default(account_id: &str, username: &str) -> Self {
        let default_email = if username.contains('@') {
            username.to_string()
        } else {
            format!("{}@localhost", account_id)
        };

        let mut identities = HashMap::new();
        identities.insert(
            "default".to_string(),
            Identity {
                id: "default".to_string(),
                name: "Default User".to_string(),
                email: default_email,
                reply_to: None,
                bcc: None,
                text_signature: None,
                html_signature: None,
                may_delete: false,
            },
        );

        Self {
            identities,
            state_version: 1,
        }
    }
}

/// Trait for identity persistence
#[async_trait]
pub trait IdentityStore: Send + Sync {
    /// Return all identities for an account (pre-populates default if absent)
    async fn list_identities(
        &self,
        account_id: &str,
        username: &str,
    ) -> anyhow::Result<Vec<Identity>>;

    /// Return one identity by id, or None
    async fn get_identity(
        &self,
        account_id: &str,
        username: &str,
        id: &str,
    ) -> anyhow::Result<Option<Identity>>;

    /// Create a new identity, returning the stored object
    async fn create_identity(
        &self,
        account_id: &str,
        username: &str,
        identity: Identity,
    ) -> anyhow::Result<Identity>;

    /// Update an identity via a flat JSON patch (top-level keys only), returning the updated object
    async fn update_identity(
        &self,
        account_id: &str,
        username: &str,
        id: &str,
        patch: &serde_json::Value,
    ) -> anyhow::Result<Identity>;

    /// Delete an identity by id; caller must reject "default" before calling
    async fn delete_identity(
        &self,
        account_id: &str,
        username: &str,
        id: &str,
    ) -> anyhow::Result<()>;

    /// Return the current state token for an account
    async fn state_token(&self, account_id: &str, username: &str) -> anyhow::Result<String>;
}

/// Filesystem-backed identity store.
///
/// Each account's identities are persisted to
/// `{base_dir}/identities/{account_id}.json`.
pub struct FileIdentityStore {
    base_dir: PathBuf,
}

impl FileIdentityStore {
    /// Create a new store rooted at `base_dir`.
    pub fn new(base_dir: impl Into<PathBuf>) -> Self {
        Self {
            base_dir: base_dir.into(),
        }
    }

    fn account_path(&self, account_id: &str) -> PathBuf {
        self.base_dir
            .join("identities")
            .join(format!("{}.json", account_id))
    }

    async fn load(&self, account_id: &str, username: &str) -> anyhow::Result<IdentityAccountState> {
        let path = self.account_path(account_id);
        if !path.exists() {
            return Ok(IdentityAccountState::new_with_default(account_id, username));
        }
        let bytes = tokio::fs::read(&path).await?;
        let state: IdentityAccountState = serde_json::from_slice(&bytes)?;
        Ok(state)
    }

    async fn save(&self, account_id: &str, state: &IdentityAccountState) -> anyhow::Result<()> {
        let path = self.account_path(account_id);
        if let Some(parent) = path.parent() {
            tokio::fs::create_dir_all(parent).await?;
        }
        let bytes = serde_json::to_vec_pretty(state)?;
        tokio::fs::write(&path, bytes).await?;
        Ok(())
    }
}

#[async_trait]
impl IdentityStore for FileIdentityStore {
    async fn list_identities(
        &self,
        account_id: &str,
        username: &str,
    ) -> anyhow::Result<Vec<Identity>> {
        let state = self.load(account_id, username).await?;
        Ok(state.identities.into_values().collect())
    }

    async fn get_identity(
        &self,
        account_id: &str,
        username: &str,
        id: &str,
    ) -> anyhow::Result<Option<Identity>> {
        let state = self.load(account_id, username).await?;
        Ok(state.identities.get(id).cloned())
    }

    async fn create_identity(
        &self,
        account_id: &str,
        username: &str,
        identity: Identity,
    ) -> anyhow::Result<Identity> {
        let mut state = self.load(account_id, username).await?;
        state
            .identities
            .insert(identity.id.clone(), identity.clone());
        state.state_version += 1;
        self.save(account_id, &state).await?;
        Ok(identity)
    }

    async fn update_identity(
        &self,
        account_id: &str,
        username: &str,
        id: &str,
        patch: &serde_json::Value,
    ) -> anyhow::Result<Identity> {
        let mut state = self.load(account_id, username).await?;
        let existing = state
            .identities
            .get(id)
            .cloned()
            .ok_or_else(|| anyhow::anyhow!("Identity '{}' not found", id))?;

        // Serialize current identity to a mutable JSON value, apply the JMAP
        // patch (top-level "/fieldName" paths), then deserialize back.
        let mut current_json = serde_json::to_value(&existing)?;
        if let (Some(obj), Some(patch_obj)) = (current_json.as_object_mut(), patch.as_object()) {
            for (path_key, value) in patch_obj {
                // JMAP patch keys are "/fieldName"; strip leading '/'
                let field = path_key.trim_start_matches('/');
                obj.insert(field.to_string(), value.clone());
            }
        }
        let mut updated: Identity = serde_json::from_value(current_json)?;

        // Preserve immutable fields
        updated.id = existing.id.clone();
        if id == "default" {
            updated.may_delete = false;
        }

        state.identities.insert(id.to_string(), updated.clone());
        state.state_version += 1;
        self.save(account_id, &state).await?;
        Ok(updated)
    }

    async fn delete_identity(
        &self,
        account_id: &str,
        username: &str,
        id: &str,
    ) -> anyhow::Result<()> {
        let mut state = self.load(account_id, username).await?;
        if state.identities.remove(id).is_none() {
            return Err(anyhow::anyhow!("Identity '{}' not found", id));
        }
        state.state_version += 1;
        self.save(account_id, &state).await?;
        Ok(())
    }

    async fn state_token(&self, account_id: &str, username: &str) -> anyhow::Result<String> {
        let state = self.load(account_id, username).await?;
        Ok(state.state_version.to_string())
    }
}

// ─── JMAP types ──────────────────────────────────────────────────────────────

/// Identity object
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Identity {
    /// Unique identifier
    pub id: String,
    /// Display name
    pub name: String,
    /// Email address
    pub email: String,
    /// Reply-to address
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reply_to: Option<Vec<crate::types::EmailAddress>>,
    /// Bcc address (auto-bcc on sends)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bcc: Option<Vec<crate::types::EmailAddress>>,
    /// Text signature
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text_signature: Option<String>,
    /// HTML signature
    #[serde(skip_serializing_if = "Option::is_none")]
    pub html_signature: Option<String>,
    /// May delete
    pub may_delete: bool,
}

/// Identity/get request
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IdentityGetRequest {
    pub account_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ids: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub properties: Option<Vec<String>>,
}

/// Identity/get response
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IdentityGetResponse {
    pub account_id: String,
    pub state: String,
    pub list: Vec<Identity>,
    pub not_found: Vec<String>,
}

/// Identity/set request
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IdentitySetRequest {
    pub account_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub if_in_state: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub create: Option<HashMap<String, IdentityObject>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub update: Option<HashMap<String, serde_json::Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub destroy: Option<Vec<String>>,
}

/// Identity object for creation
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IdentityObject {
    pub name: String,
    pub email: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reply_to: Option<Vec<crate::types::EmailAddress>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bcc: Option<Vec<crate::types::EmailAddress>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text_signature: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub html_signature: Option<String>,
}

/// Identity/set response
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IdentitySetResponse {
    pub account_id: String,
    pub old_state: String,
    pub new_state: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created: Option<HashMap<String, Identity>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated: Option<HashMap<String, Option<Identity>>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub destroyed: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub not_created: Option<HashMap<String, JmapSetError>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub not_updated: Option<HashMap<String, JmapSetError>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub not_destroyed: Option<HashMap<String, JmapSetError>>,
}

/// Identity/changes request
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IdentityChangesRequest {
    pub account_id: String,
    pub since_state: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_changes: Option<u64>,
}

/// Identity/changes response
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IdentityChangesResponse {
    pub account_id: String,
    pub old_state: String,
    pub new_state: String,
    pub has_more_changes: bool,
    pub created: Vec<String>,
    pub updated: Vec<String>,
    pub destroyed: Vec<String>,
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

/// Minimal email format validation: must contain exactly one '@' with non-empty
/// local-part and domain.
fn is_valid_email(email: &str) -> bool {
    let at_count = email.chars().filter(|&c| c == '@').count();
    if at_count != 1 {
        return false;
    }
    let mut parts = email.splitn(2, '@');
    let local = parts.next().unwrap_or("");
    let domain = parts.next().unwrap_or("");
    !local.is_empty() && !domain.is_empty()
}

// ─── Method handlers ─────────────────────────────────────────────────────────

/// Handle Identity/get method
pub async fn identity_get(
    request: IdentityGetRequest,
    _message_store: &dyn MessageStore,
    identity_store: &dyn IdentityStore,
    principal: &Principal,
) -> anyhow::Result<IdentityGetResponse> {
    ensure_account_ownership(&request.account_id, principal)?;

    let state = identity_store
        .state_token(&request.account_id, &principal.username)
        .await?;

    let mut list = Vec::new();
    let mut not_found = Vec::new();

    match request.ids {
        None => {
            let all = identity_store
                .list_identities(&request.account_id, &principal.username)
                .await?;
            list.extend(all);
        }
        Some(ids) => {
            for id in ids {
                match identity_store
                    .get_identity(&request.account_id, &principal.username, &id)
                    .await?
                {
                    Some(identity) => list.push(identity),
                    None => not_found.push(id),
                }
            }
        }
    }

    Ok(IdentityGetResponse {
        account_id: request.account_id,
        state,
        list,
        not_found,
    })
}

/// Handle Identity/set method
pub async fn identity_set(
    request: IdentitySetRequest,
    _message_store: &dyn MessageStore,
    identity_store: &dyn IdentityStore,
    principal: &Principal,
) -> anyhow::Result<IdentitySetResponse> {
    ensure_account_ownership(&request.account_id, principal)?;

    let old_state = identity_store
        .state_token(&request.account_id, &principal.username)
        .await?;

    // Per RFC 8620 §5.3, if_in_state mismatch aborts the entire call
    if let Some(ref expected) = request.if_in_state {
        if *expected != old_state {
            return Err(anyhow::anyhow!(
                "stateMismatch: expected state '{}', current state is '{}'",
                expected,
                old_state
            ));
        }
    }

    let mut created: HashMap<String, Identity> = HashMap::new();
    let mut updated: HashMap<String, Option<Identity>> = HashMap::new();
    let mut destroyed: Vec<String> = Vec::new();
    let mut not_created: HashMap<String, JmapSetError> = HashMap::new();
    let mut not_updated: HashMap<String, JmapSetError> = HashMap::new();
    let mut not_destroyed: HashMap<String, JmapSetError> = HashMap::new();

    // ── Creates ──────────────────────────────────────────────────────────────
    if let Some(create_map) = request.create {
        for (creation_id, identity_obj) in create_map {
            if !is_valid_email(&identity_obj.email) {
                not_created.insert(
                    creation_id,
                    JmapSetError {
                        error_type: "invalidProperties".to_string(),
                        description: Some(format!(
                            "Invalid email address: '{}'",
                            identity_obj.email
                        )),
                    },
                );
                continue;
            }
            let new_id = uuid::Uuid::new_v4().to_string();
            let new_identity = Identity {
                id: new_id,
                name: identity_obj.name,
                email: identity_obj.email,
                reply_to: identity_obj.reply_to,
                bcc: identity_obj.bcc,
                text_signature: identity_obj.text_signature,
                html_signature: identity_obj.html_signature,
                may_delete: true,
            };
            match identity_store
                .create_identity(&request.account_id, &principal.username, new_identity)
                .await
            {
                Ok(stored) => {
                    created.insert(creation_id, stored);
                }
                Err(e) => {
                    not_created.insert(
                        creation_id,
                        JmapSetError {
                            error_type: "serverFail".to_string(),
                            description: Some(format!("Failed to create identity: {}", e)),
                        },
                    );
                }
            }
        }
    }

    // ── Updates ──────────────────────────────────────────────────────────────
    if let Some(update_map) = request.update {
        for (id, patch) in update_map {
            match identity_store
                .update_identity(&request.account_id, &principal.username, &id, &patch)
                .await
            {
                Ok(stored) => {
                    updated.insert(id, Some(stored));
                }
                Err(e) => {
                    let err_msg = e.to_string();
                    let error_type = if err_msg.contains("not found") {
                        "notFound"
                    } else {
                        "serverFail"
                    };
                    not_updated.insert(
                        id,
                        JmapSetError {
                            error_type: error_type.to_string(),
                            description: Some(err_msg),
                        },
                    );
                }
            }
        }
    }

    // ── Destroys ─────────────────────────────────────────────────────────────
    if let Some(destroy_ids) = request.destroy {
        for id in destroy_ids {
            if id == "default" {
                not_destroyed.insert(
                    id,
                    JmapSetError {
                        error_type: "forbidden".to_string(),
                        description: Some("Cannot delete default identity".to_string()),
                    },
                );
                continue;
            }
            match identity_store
                .delete_identity(&request.account_id, &principal.username, &id)
                .await
            {
                Ok(()) => destroyed.push(id),
                Err(e) => {
                    let err_msg = e.to_string();
                    let error_type = if err_msg.contains("not found") {
                        "notFound"
                    } else {
                        "serverFail"
                    };
                    not_destroyed.insert(
                        id,
                        JmapSetError {
                            error_type: error_type.to_string(),
                            description: Some(err_msg),
                        },
                    );
                }
            }
        }
    }

    let new_state = identity_store
        .state_token(&request.account_id, &principal.username)
        .await?;

    Ok(IdentitySetResponse {
        account_id: request.account_id,
        old_state,
        new_state,
        created: if created.is_empty() {
            None
        } else {
            Some(created)
        },
        updated: if updated.is_empty() {
            None
        } else {
            Some(updated)
        },
        destroyed: if destroyed.is_empty() {
            None
        } else {
            Some(destroyed)
        },
        not_created: if not_created.is_empty() {
            None
        } else {
            Some(not_created)
        },
        not_updated: if not_updated.is_empty() {
            None
        } else {
            Some(not_updated)
        },
        not_destroyed: if not_destroyed.is_empty() {
            None
        } else {
            Some(not_destroyed)
        },
    })
}

/// Handle Identity/changes method
pub async fn identity_changes(
    request: IdentityChangesRequest,
    _message_store: &dyn MessageStore,
    identity_store: &dyn IdentityStore,
    principal: &Principal,
) -> anyhow::Result<IdentityChangesResponse> {
    ensure_account_ownership(&request.account_id, principal)?;

    let new_state = identity_store
        .state_token(&request.account_id, &principal.username)
        .await?;
    let old_state = request.since_state;

    // Slice A: we report the current state token but do not track per-object
    // change history. Callers should re-fetch all identities when the state
    // token differs from what they last saw.
    Ok(IdentityChangesResponse {
        account_id: request.account_id,
        old_state,
        new_state,
        has_more_changes: false,
        created: Vec::new(),
        updated: Vec::new(),
        destroyed: Vec::new(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use rusmes_storage::backends::filesystem::FilesystemBackend;
    use rusmes_storage::StorageBackend;
    use std::path::PathBuf;

    fn test_principal() -> crate::types::Principal {
        crate::types::Principal {
            username: "alice@example.com".to_string(),
            account_id: "acc1".to_string(),
            scopes: vec![crate::types::SCOPE_ADMIN.to_string()],
        }
    }

    fn create_test_store() -> std::sync::Arc<dyn MessageStore> {
        let backend = FilesystemBackend::new(PathBuf::from("/tmp/rusmes-test-storage"));
        backend.message_store()
    }

    fn create_identity_store(sub: &str) -> FileIdentityStore {
        let mut dir = std::env::temp_dir();
        dir.push(format!("rusmes-identity-test-{}", sub));
        FileIdentityStore::new(dir)
    }

    // ── Required new tests ────────────────────────────────────────────────────

    #[tokio::test]
    async fn test_identity_create_and_get() {
        let msg_store = create_test_store();
        let id_store = create_identity_store("create_and_get");
        let principal = test_principal();

        let mut create_map = HashMap::new();
        create_map.insert(
            "c1".to_string(),
            IdentityObject {
                name: "Alice".to_string(),
                email: "alice@example.com".to_string(),
                reply_to: None,
                bcc: None,
                text_signature: None,
                html_signature: None,
            },
        );
        let set_resp = identity_set(
            IdentitySetRequest {
                account_id: "acc1".to_string(),
                if_in_state: None,
                create: Some(create_map),
                update: None,
                destroy: None,
            },
            msg_store.as_ref(),
            &id_store,
            &principal,
        )
        .await
        .unwrap();

        assert!(set_resp.not_created.is_none(), "create should succeed");
        let created = set_resp.created.unwrap();
        assert_eq!(created.len(), 1);
        let stored = created.get("c1").unwrap();
        assert_eq!(stored.name, "Alice");
        assert_eq!(stored.email, "alice@example.com");
        assert!(stored.may_delete);

        // Fetch it back by id
        let get_resp = identity_get(
            IdentityGetRequest {
                account_id: "acc1".to_string(),
                ids: Some(vec![stored.id.clone()]),
                properties: None,
            },
            msg_store.as_ref(),
            &id_store,
            &principal,
        )
        .await
        .unwrap();
        assert_eq!(get_resp.list.len(), 1);
        assert_eq!(get_resp.list[0].email, "alice@example.com");
    }

    #[tokio::test]
    async fn test_identity_update_name() {
        let msg_store = create_test_store();
        let id_store = create_identity_store("update_name");
        let principal = test_principal();

        // Create first
        let mut create_map = HashMap::new();
        create_map.insert(
            "c1".to_string(),
            IdentityObject {
                name: "Original".to_string(),
                email: "orig@example.com".to_string(),
                reply_to: None,
                bcc: None,
                text_signature: None,
                html_signature: None,
            },
        );
        let set_resp = identity_set(
            IdentitySetRequest {
                account_id: "acc1".to_string(),
                if_in_state: None,
                create: Some(create_map),
                update: None,
                destroy: None,
            },
            msg_store.as_ref(),
            &id_store,
            &principal,
        )
        .await
        .unwrap();
        let new_id = set_resp.created.unwrap().get("c1").unwrap().id.clone();

        // Update the name
        let mut update_map = HashMap::new();
        update_map.insert(new_id.clone(), serde_json::json!({"/name": "Updated Name"}));
        let upd_resp = identity_set(
            IdentitySetRequest {
                account_id: "acc1".to_string(),
                if_in_state: None,
                create: None,
                update: Some(update_map),
                destroy: None,
            },
            msg_store.as_ref(),
            &id_store,
            &principal,
        )
        .await
        .unwrap();

        assert!(upd_resp.not_updated.is_none(), "update should succeed");
        let upd = upd_resp.updated.unwrap();
        let id_obj = upd.get(&new_id).unwrap().as_ref().unwrap();
        assert_eq!(id_obj.name, "Updated Name");
    }

    #[tokio::test]
    async fn test_identity_destroy_custom() {
        let msg_store = create_test_store();
        let id_store = create_identity_store("destroy_custom");
        let principal = test_principal();

        // Create an identity to destroy
        let mut create_map = HashMap::new();
        create_map.insert(
            "c1".to_string(),
            IdentityObject {
                name: "To Be Deleted".to_string(),
                email: "delete@example.com".to_string(),
                reply_to: None,
                bcc: None,
                text_signature: None,
                html_signature: None,
            },
        );
        let set_resp = identity_set(
            IdentitySetRequest {
                account_id: "acc1".to_string(),
                if_in_state: None,
                create: Some(create_map),
                update: None,
                destroy: None,
            },
            msg_store.as_ref(),
            &id_store,
            &principal,
        )
        .await
        .unwrap();
        let new_id = set_resp.created.unwrap().get("c1").unwrap().id.clone();

        // Destroy it
        let del_resp = identity_set(
            IdentitySetRequest {
                account_id: "acc1".to_string(),
                if_in_state: None,
                create: None,
                update: None,
                destroy: Some(vec![new_id.clone()]),
            },
            msg_store.as_ref(),
            &id_store,
            &principal,
        )
        .await
        .unwrap();

        assert!(del_resp.not_destroyed.is_none(), "destroy should succeed");
        let destroyed = del_resp.destroyed.unwrap();
        assert!(destroyed.contains(&new_id));

        // Verify gone
        let get_resp = identity_get(
            IdentityGetRequest {
                account_id: "acc1".to_string(),
                ids: Some(vec![new_id.clone()]),
                properties: None,
            },
            msg_store.as_ref(),
            &id_store,
            &principal,
        )
        .await
        .unwrap();
        assert_eq!(get_resp.not_found, vec![new_id]);
    }

    #[tokio::test]
    async fn test_identity_destroy_default_rejected() {
        let msg_store = create_test_store();
        let id_store = create_identity_store("destroy_default_rejected");
        let principal = test_principal();

        let resp = identity_set(
            IdentitySetRequest {
                account_id: "acc1".to_string(),
                if_in_state: None,
                create: None,
                update: None,
                destroy: Some(vec!["default".to_string()]),
            },
            msg_store.as_ref(),
            &id_store,
            &principal,
        )
        .await
        .unwrap();

        assert!(resp.not_destroyed.is_some());
        let errors = resp.not_destroyed.unwrap();
        assert_eq!(errors.get("default").unwrap().error_type, "forbidden");
    }

    #[tokio::test]
    async fn test_identity_state_mismatch() {
        let msg_store = create_test_store();
        let id_store = create_identity_store("state_mismatch");
        let principal = test_principal();

        // Trigger a create to advance state past "1"
        let mut create_map = HashMap::new();
        create_map.insert(
            "c1".to_string(),
            IdentityObject {
                name: "Trigger".to_string(),
                email: "trigger@example.com".to_string(),
                reply_to: None,
                bcc: None,
                text_signature: None,
                html_signature: None,
            },
        );
        identity_set(
            IdentitySetRequest {
                account_id: "acc1".to_string(),
                if_in_state: None,
                create: Some(create_map),
                update: None,
                destroy: None,
            },
            msg_store.as_ref(),
            &id_store,
            &principal,
        )
        .await
        .unwrap();

        // Submit with wrong state
        let result = identity_set(
            IdentitySetRequest {
                account_id: "acc1".to_string(),
                if_in_state: Some("999".to_string()),
                create: None,
                update: None,
                destroy: None,
            },
            msg_store.as_ref(),
            &id_store,
            &principal,
        )
        .await;

        assert!(result.is_err(), "wrong state should return Err");
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("stateMismatch"),
            "error should mention stateMismatch: {}",
            err_msg
        );
    }

    #[tokio::test]
    async fn test_identity_full_roundtrip() {
        let msg_store = create_test_store();
        let id_store = create_identity_store("full_roundtrip");
        let principal = test_principal();

        // 1. Initial get — only default
        let get1 = identity_get(
            IdentityGetRequest {
                account_id: "acc1".to_string(),
                ids: None,
                properties: None,
            },
            msg_store.as_ref(),
            &id_store,
            &principal,
        )
        .await
        .unwrap();
        assert_eq!(get1.list.len(), 1);
        assert_eq!(get1.list[0].id, "default");
        assert!(!get1.list[0].may_delete);
        let state_after_default = get1.state.clone();

        // 2. Create a new identity
        let mut create_map = HashMap::new();
        create_map.insert(
            "newone".to_string(),
            IdentityObject {
                name: "Work".to_string(),
                email: "work@company.com".to_string(),
                reply_to: None,
                bcc: None,
                text_signature: Some("Regards,\nAlice".to_string()),
                html_signature: None,
            },
        );
        let set1 = identity_set(
            IdentitySetRequest {
                account_id: "acc1".to_string(),
                if_in_state: Some(state_after_default.clone()),
                create: Some(create_map),
                update: None,
                destroy: None,
            },
            msg_store.as_ref(),
            &id_store,
            &principal,
        )
        .await
        .unwrap();
        assert!(set1.not_created.is_none());
        let work_id = set1.created.unwrap().get("newone").unwrap().id.clone();
        let state_after_create = set1.new_state.clone();
        assert_ne!(state_after_default, state_after_create);

        // 3. Update it
        let mut upd_map = HashMap::new();
        upd_map.insert(
            work_id.clone(),
            serde_json::json!({"/name": "Work (updated)"}),
        );
        let set2 = identity_set(
            IdentitySetRequest {
                account_id: "acc1".to_string(),
                if_in_state: Some(state_after_create.clone()),
                create: None,
                update: Some(upd_map),
                destroy: None,
            },
            msg_store.as_ref(),
            &id_store,
            &principal,
        )
        .await
        .unwrap();
        assert!(set2.not_updated.is_none());
        let upd_identity = set2
            .updated
            .unwrap()
            .get(&work_id)
            .unwrap()
            .as_ref()
            .unwrap()
            .clone();
        assert_eq!(upd_identity.name, "Work (updated)");

        // 4. Destroy it
        let set3 = identity_set(
            IdentitySetRequest {
                account_id: "acc1".to_string(),
                if_in_state: None,
                create: None,
                update: None,
                destroy: Some(vec![work_id.clone()]),
            },
            msg_store.as_ref(),
            &id_store,
            &principal,
        )
        .await
        .unwrap();
        assert!(set3.not_destroyed.is_none());
        assert_eq!(set3.destroyed.unwrap(), vec![work_id.clone()]);

        // 5. Verify only default remains
        let get_final = identity_get(
            IdentityGetRequest {
                account_id: "acc1".to_string(),
                ids: None,
                properties: None,
            },
            msg_store.as_ref(),
            &id_store,
            &principal,
        )
        .await
        .unwrap();
        assert_eq!(get_final.list.len(), 1);
        assert_eq!(get_final.list[0].id, "default");
    }

    // ── Retained legacy tests (updated for new signatures) ───────────────────

    #[tokio::test]
    async fn test_identity_get() {
        let msg_store = create_test_store();
        let id_store = create_identity_store("get_default");
        let principal = test_principal();
        let request = IdentityGetRequest {
            account_id: "acc1".to_string(),
            ids: Some(vec!["default".to_string()]),
            properties: None,
        };

        let response = identity_get(request, msg_store.as_ref(), &id_store, &principal)
            .await
            .unwrap();
        assert_eq!(response.list.len(), 1);
        assert_eq!(response.list[0].id, "default");
    }

    #[tokio::test]
    async fn test_identity_set_create() {
        let msg_store = create_test_store();
        let id_store = create_identity_store("set_create");
        let principal = test_principal();

        let mut create_map = HashMap::new();
        create_map.insert(
            "new1".to_string(),
            IdentityObject {
                name: "John Doe".to_string(),
                email: "john@example.com".to_string(),
                reply_to: None,
                bcc: None,
                text_signature: Some("Best regards,\nJohn".to_string()),
                html_signature: None,
            },
        );

        let request = IdentitySetRequest {
            account_id: "acc1".to_string(),
            if_in_state: None,
            create: Some(create_map),
            update: None,
            destroy: None,
        };

        let response = identity_set(request, msg_store.as_ref(), &id_store, &principal)
            .await
            .unwrap();
        assert!(response.created.is_some());
        assert_eq!(response.created.as_ref().unwrap().len(), 1);
    }

    #[tokio::test]
    async fn test_identity_changes() {
        let msg_store = create_test_store();
        let id_store = create_identity_store("changes");
        let principal = test_principal();
        let request = IdentityChangesRequest {
            account_id: "acc1".to_string(),
            since_state: "1".to_string(),
            max_changes: Some(50),
        };

        let response = identity_changes(request, msg_store.as_ref(), &id_store, &principal)
            .await
            .unwrap();
        assert_eq!(response.old_state, "1");
        assert!(!response.new_state.is_empty());
    }

    #[tokio::test]
    async fn test_identity_set_destroy_default() {
        let msg_store = create_test_store();
        let id_store = create_identity_store("destroy_default");
        let principal = test_principal();
        let request = IdentitySetRequest {
            account_id: "acc1".to_string(),
            if_in_state: None,
            create: None,
            update: None,
            destroy: Some(vec!["default".to_string()]),
        };

        let response = identity_set(request, msg_store.as_ref(), &id_store, &principal)
            .await
            .unwrap();
        assert!(response.not_destroyed.is_some());
        let errors = response.not_destroyed.unwrap();
        assert_eq!(errors.get("default").unwrap().error_type, "forbidden");
    }

    #[tokio::test]
    async fn test_identity_with_signature() {
        let msg_store = create_test_store();
        let id_store = create_identity_store("with_signature");
        let principal = test_principal();

        let mut create_map = HashMap::new();
        create_map.insert(
            "sig1".to_string(),
            IdentityObject {
                name: "Test User".to_string(),
                email: "test@example.com".to_string(),
                reply_to: None,
                bcc: None,
                text_signature: Some("--\nBest regards".to_string()),
                html_signature: Some("<p>Best regards</p>".to_string()),
            },
        );

        let request = IdentitySetRequest {
            account_id: "acc1".to_string(),
            if_in_state: None,
            create: Some(create_map),
            update: None,
            destroy: None,
        };

        let response = identity_set(request, msg_store.as_ref(), &id_store, &principal)
            .await
            .unwrap();
        assert!(response.created.is_some());
        let stored = response.created.as_ref().unwrap().get("sig1").unwrap();
        assert_eq!(stored.text_signature.as_deref(), Some("--\nBest regards"));
    }

    #[tokio::test]
    async fn test_identity_with_bcc() {
        let msg_store = create_test_store();
        let id_store = create_identity_store("with_bcc");
        let principal = test_principal();

        let mut create_map = HashMap::new();
        let bcc = vec![crate::types::EmailAddress::new(
            "archive@example.com".to_string(),
        )];

        create_map.insert(
            "bcc1".to_string(),
            IdentityObject {
                name: "Test User".to_string(),
                email: "test@example.com".to_string(),
                reply_to: None,
                bcc: Some(bcc),
                text_signature: None,
                html_signature: None,
            },
        );

        let request = IdentitySetRequest {
            account_id: "acc1".to_string(),
            if_in_state: None,
            create: Some(create_map),
            update: None,
            destroy: None,
        };

        let response = identity_set(request, msg_store.as_ref(), &id_store, &principal)
            .await
            .unwrap();
        assert!(response.created.is_some());
        let stored = response.created.as_ref().unwrap().get("bcc1").unwrap();
        assert!(stored.bcc.is_some());
    }

    #[tokio::test]
    async fn test_identity_get_not_found() {
        let msg_store = create_test_store();
        let id_store = create_identity_store("get_not_found");
        let principal = test_principal();
        let request = IdentityGetRequest {
            account_id: "acc1".to_string(),
            ids: Some(vec!["nonexistent".to_string()]),
            properties: None,
        };

        let response = identity_get(request, msg_store.as_ref(), &id_store, &principal)
            .await
            .unwrap();
        assert_eq!(response.not_found.len(), 1);
    }

    #[tokio::test]
    async fn test_identity_get_all() {
        let msg_store = create_test_store();
        let id_store = create_identity_store("get_all");
        let principal = test_principal();
        let request = IdentityGetRequest {
            account_id: "acc1".to_string(),
            ids: None,
            properties: None,
        };

        let response = identity_get(request, msg_store.as_ref(), &id_store, &principal)
            .await
            .unwrap();
        assert!(!response.list.is_empty());
    }

    #[tokio::test]
    async fn test_identity_set_update() {
        let msg_store = create_test_store();
        let id_store = create_identity_store("set_update_default");
        let principal = test_principal();

        let mut update_map = HashMap::new();
        update_map.insert(
            "default".to_string(),
            serde_json::json!({"/name": "New Name"}),
        );

        let request = IdentitySetRequest {
            account_id: "acc1".to_string(),
            if_in_state: None,
            create: None,
            update: Some(update_map),
            destroy: None,
        };

        let response = identity_set(request, msg_store.as_ref(), &id_store, &principal)
            .await
            .unwrap();
        // Default can be updated (only destroy is forbidden)
        assert!(response.not_updated.is_none());
        let upd = response.updated.unwrap();
        let id_obj = upd.get("default").unwrap().as_ref().unwrap();
        assert_eq!(id_obj.name, "New Name");
    }

    #[tokio::test]
    async fn test_identity_changes_state_progression() {
        let msg_store = create_test_store();
        let id_store = create_identity_store("changes_state_progression");
        let principal = test_principal();

        // Create one identity to advance the version
        let mut create_map = HashMap::new();
        create_map.insert(
            "c1".to_string(),
            IdentityObject {
                name: "Test".to_string(),
                email: "test@example.com".to_string(),
                reply_to: None,
                bcc: None,
                text_signature: None,
                html_signature: None,
            },
        );
        identity_set(
            IdentitySetRequest {
                account_id: "acc1".to_string(),
                if_in_state: None,
                create: Some(create_map),
                update: None,
                destroy: None,
            },
            msg_store.as_ref(),
            &id_store,
            &principal,
        )
        .await
        .unwrap();

        let request1 = IdentityChangesRequest {
            account_id: "acc1".to_string(),
            since_state: "1".to_string(),
            max_changes: None,
        };
        let response1 = identity_changes(request1, msg_store.as_ref(), &id_store, &principal)
            .await
            .unwrap();

        let new_state_num: u64 = response1.new_state.parse().unwrap();
        assert!(new_state_num > 1, "state should have advanced beyond 1");

        // Calling changes again with the returned new_state yields same state
        let request2 = IdentityChangesRequest {
            account_id: "acc1".to_string(),
            since_state: response1.new_state.clone(),
            max_changes: None,
        };
        let response2 = identity_changes(request2, msg_store.as_ref(), &id_store, &principal)
            .await
            .unwrap();
        assert_eq!(response1.new_state, response2.new_state);
    }

    #[tokio::test]
    async fn test_identity_default_may_not_delete() {
        let msg_store = create_test_store();
        let id_store = create_identity_store("default_may_not_delete");
        let principal = test_principal();
        let request = IdentityGetRequest {
            account_id: "acc1".to_string(),
            ids: Some(vec!["default".to_string()]),
            properties: None,
        };

        let response = identity_get(request, msg_store.as_ref(), &id_store, &principal)
            .await
            .unwrap();
        assert!(!response.list[0].may_delete);
    }

    #[tokio::test]
    async fn test_identity_with_reply_to() {
        let msg_store = create_test_store();
        let id_store = create_identity_store("with_reply_to");
        let principal = test_principal();

        let mut create_map = HashMap::new();
        let reply_to = vec![crate::types::EmailAddress::new(
            "support@example.com".to_string(),
        )];

        create_map.insert(
            "replyto1".to_string(),
            IdentityObject {
                name: "Support".to_string(),
                email: "noreply@example.com".to_string(),
                reply_to: Some(reply_to),
                bcc: None,
                text_signature: None,
                html_signature: None,
            },
        );

        let request = IdentitySetRequest {
            account_id: "acc1".to_string(),
            if_in_state: None,
            create: Some(create_map),
            update: None,
            destroy: None,
        };

        let response = identity_set(request, msg_store.as_ref(), &id_store, &principal)
            .await
            .unwrap();
        assert!(response.created.is_some());
        let stored = response.created.as_ref().unwrap().get("replyto1").unwrap();
        assert!(stored.reply_to.is_some());
    }

    #[tokio::test]
    async fn test_identity_invalid_email_rejected() {
        let msg_store = create_test_store();
        let id_store = create_identity_store("invalid_email");
        let principal = test_principal();

        let mut create_map = HashMap::new();
        create_map.insert(
            "bad1".to_string(),
            IdentityObject {
                name: "Bad".to_string(),
                email: "not-an-email".to_string(),
                reply_to: None,
                bcc: None,
                text_signature: None,
                html_signature: None,
            },
        );

        let response = identity_set(
            IdentitySetRequest {
                account_id: "acc1".to_string(),
                if_in_state: None,
                create: Some(create_map),
                update: None,
                destroy: None,
            },
            msg_store.as_ref(),
            &id_store,
            &principal,
        )
        .await
        .unwrap();
        assert!(response.not_created.is_some());
        let err = response.not_created.unwrap();
        assert_eq!(err.get("bad1").unwrap().error_type, "invalidProperties");
    }
}