rusmes-imap 0.1.2

Async IMAP4rev2 server for RusMES — RFC 9051 compliant with CONDSTORE, QRESYNC, UIDPLUS, MOVE, IDLE, NAMESPACE, and SPECIAL-USE extensions
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
//! IMAP message command handlers
//!
//! Covers: FETCH, STORE, SEARCH, APPEND, COPY, MOVE, EXPUNGE, CLOSE,
//!         UID FETCH, UID STORE, UID SEARCH, UID COPY, UID MOVE, UID EXPUNGE

use crate::command::{StoreMode, UidSubcommand};
use crate::handler::HandlerContext;
use crate::mailbox_registry::MailboxEvent;
use crate::response::ImapResponse;
use crate::session::{ImapSession, ImapState};
use rusmes_proto::MessageId;
use rusmes_storage::{MessageFlags, MessageMetadata, SearchCriteria};

/// Handle FETCH command
pub(crate) async fn handle_fetch(
    ctx: &HandlerContext,
    session: &ImapSession,
    tag: &str,
    sequence: &str,
    items: &[String],
) -> anyhow::Result<ImapResponse> {
    // Must have a mailbox selected
    let mailbox_id = match session.state() {
        ImapState::Selected { mailbox_id } => mailbox_id,
        _ => return Ok(ImapResponse::no(tag, "No mailbox selected")),
    };

    // Get all messages in the mailbox
    let all_messages = ctx.message_store.get_mailbox_messages(mailbox_id).await?;

    // Parse sequence set and map to messages
    let sequence_numbers = parse_sequence_numbers(sequence, all_messages.len())?;

    // Fetch each message
    let mut responses = Vec::new();
    for seq_num in sequence_numbers {
        // Sequence numbers are 1-based, vector indices are 0-based
        if seq_num > 0 && seq_num <= all_messages.len() {
            let metadata = &all_messages[seq_num - 1];

            // Get the full message content
            if let Some(mail) = ctx.message_store.get_message(metadata.message_id()).await? {
                // Build FETCH response based on requested items
                let fetch_items = build_fetch_items(&mail, metadata, items).await;
                responses.push(format!("* {} FETCH ({})", seq_num, fetch_items));
            }
        }
    }

    // Combine responses
    let mut full_response = responses.join("\r\n");
    if !full_response.is_empty() {
        full_response.push_str("\r\n");
    }
    full_response.push_str(&format!("{} OK FETCH completed", tag));

    Ok(ImapResponse::new(None, "", full_response))
}

/// Handle STORE command
pub(crate) async fn handle_store(
    ctx: &HandlerContext,
    session: &ImapSession,
    tag: &str,
    sequence: &str,
    mode: StoreMode,
    flags: &[String],
) -> anyhow::Result<ImapResponse> {
    // Must have a mailbox selected
    let mailbox_id = match session.state() {
        ImapState::Selected { mailbox_id } => *mailbox_id,
        _ => return Ok(ImapResponse::no(tag, "No mailbox selected")),
    };

    // Parse sequence set
    let message_ids = parse_sequence_set(sequence)?;

    // Build MessageFlags from string flags
    let msg_flags = build_message_flags(flags);

    // Apply flags based on mode
    // For now, we'll just set the flags (simplified implementation)
    // In a real implementation, we'd need to handle +FLAGS and -FLAGS properly
    if !message_ids.is_empty() {
        // NOTE: parse_sequence_set currently always returns an empty Vec (seq-number lookup
        // is not fully wired), so this block is effectively a no-op for non-UID STORE. The
        // UID variant (handle_uid_store) is the primary code path.
        match mode {
            StoreMode::Replace => {
                ctx.message_store.set_flags(&message_ids, msg_flags).await?;
            }
            StoreMode::Add => {
                // Would need to fetch current flags and merge
                ctx.message_store.set_flags(&message_ids, msg_flags).await?;
            }
            StoreMode::Remove => {
                // Would need to fetch current flags and remove
                ctx.message_store.set_flags(&message_ids, msg_flags).await?;
            }
        }

        // Broadcast FlagsChanged events. We need UIDs, not MessageIds, so we must look them
        // up. To avoid a fragile MessageId round-trip after set_flags moves files from new/
        // to cur/, we capture the UIDs from the metadata BEFORE calling set_flags.
        // (handle_store currently never reaches here because parse_sequence_set returns []).
        let all_metadata = ctx.message_store.get_mailbox_messages(&mailbox_id).await?;
        let flag_strings: Vec<String> = flags.to_vec();
        let target_uids: Vec<u32> = all_metadata
            .iter()
            .filter(|m| message_ids.contains(m.message_id()))
            .map(|m| m.uid())
            .collect();
        for uid in target_uids {
            ctx.mailbox_registry.publish(
                mailbox_id,
                MailboxEvent::FlagsChanged {
                    uid,
                    flags: flag_strings.clone(),
                },
            );
        }
    }

    Ok(ImapResponse::ok(tag, "STORE completed"))
}

/// Handle SEARCH command
pub(crate) async fn handle_search(
    ctx: &HandlerContext,
    session: &ImapSession,
    tag: &str,
    criteria: &[String],
) -> anyhow::Result<ImapResponse> {
    // Must have a mailbox selected
    let mailbox_id = match session.state() {
        ImapState::Selected { mailbox_id } => mailbox_id,
        _ => return Ok(ImapResponse::no(tag, "No mailbox selected")),
    };

    // Parse search criteria
    let search_criteria = parse_search_criteria(criteria);

    // Perform search
    let message_ids = ctx
        .message_store
        .search(mailbox_id, search_criteria)
        .await?;

    // Build response
    let ids_str: Vec<String> = message_ids.iter().map(|id| id.to_string()).collect();
    let response = format!(
        "* SEARCH {}\r\n{} OK SEARCH completed",
        ids_str.join(" "),
        tag
    );

    Ok(ImapResponse::new(None, "", response))
}

/// Handle APPEND command
#[allow(clippy::too_many_arguments)]
pub(crate) async fn handle_append(
    ctx: &HandlerContext,
    session: &ImapSession,
    tag: &str,
    mailbox: &str,
    flags: &[String],
    _date_time: Option<&str>,
    message_literal: &[u8],
) -> anyhow::Result<ImapResponse> {
    // Must be authenticated
    if !matches!(
        session.state(),
        ImapState::Authenticated | ImapState::Selected { .. }
    ) {
        return Ok(ImapResponse::no(tag, "Not authenticated"));
    }

    // Get username from session
    let username = match &session.username {
        Some(u) => u.clone(),
        None => return Ok(ImapResponse::no(tag, "No username in session")),
    };

    // Find the mailbox
    let mailboxes = ctx.mailbox_store.list_mailboxes(&username).await?;
    let mailbox_obj = mailboxes.iter().find(|m| m.path().name() == Some(mailbox));

    let mailbox_id = match mailbox_obj {
        Some(mb) => *mb.id(),
        None => return Ok(ImapResponse::no(tag, "[TRYCREATE] Mailbox does not exist")),
    };

    // Parse the message literal into a Mail object
    // For APPEND, we need to parse the raw message data
    let message_data = bytes::Bytes::from(message_literal.to_vec());

    // Parse headers and body from the raw message
    let (headers, body) = parse_message_data(&message_data)?;

    // Create MimeMessage
    use rusmes_proto::{MessageBody, MimeMessage};
    let mime_message = MimeMessage::new(headers, MessageBody::Small(body));

    // Extract sender and recipients from headers
    let sender = extract_sender_from_headers(mime_message.headers());
    let recipients = extract_recipients_from_headers(mime_message.headers());

    // Create Mail object
    use rusmes_proto::Mail;
    let mut mail = Mail::new(sender, recipients, mime_message, None, None);

    // Set message state to LocalDelivery since we're storing directly
    use rusmes_proto::MailState;
    mail.state = MailState::LocalDelivery;

    // Append message to mailbox
    let metadata = ctx.message_store.append_message(&mailbox_id, mail).await?;

    // Update flags if provided
    if !flags.is_empty() {
        let msg_flags = build_message_flags(flags);
        ctx.message_store
            .set_flags(&[*metadata.message_id()], msg_flags)
            .await?;
    }

    // Broadcast EXISTS update to all sessions watching this mailbox (RFC 3501 §5.2).
    // We get the new count from the metadata store after the append has landed.
    let new_count = ctx
        .metadata_store
        .get_mailbox_counters(&mailbox_id)
        .await
        .map(|c| c.exists)
        .unwrap_or(0);
    ctx.mailbox_registry
        .publish(mailbox_id, MailboxEvent::Exists { count: new_count });

    // Return success with APPENDUID response code (RFC 4315)
    let uid_validity = mailbox_obj.map(|mb| mb.uid_validity()).unwrap_or(0);
    Ok(ImapResponse::ok(
        tag,
        format!(
            "[APPENDUID {} {}] APPEND completed",
            uid_validity,
            metadata.uid()
        ),
    ))
}

/// Handle COPY command
pub(crate) async fn handle_copy(
    ctx: &HandlerContext,
    session: &ImapSession,
    tag: &str,
    sequence: &str,
    dest_mailbox: &str,
) -> anyhow::Result<ImapResponse> {
    // Must have a mailbox selected
    let _source_mailbox_id = match session.state() {
        ImapState::Selected { mailbox_id } => mailbox_id,
        _ => return Ok(ImapResponse::no(tag, "No mailbox selected")),
    };

    // Get username from session
    let username = match &session.username {
        Some(u) => u.clone(),
        None => return Ok(ImapResponse::no(tag, "No username in session")),
    };

    // Find the destination mailbox
    let mailboxes = ctx.mailbox_store.list_mailboxes(&username).await?;
    let dest_mailbox_obj = mailboxes
        .iter()
        .find(|m| m.path().name() == Some(dest_mailbox));

    let dest_mailbox_id = match dest_mailbox_obj {
        Some(mb) => mb.id(),
        None => {
            return Ok(ImapResponse::no(
                tag,
                "[TRYCREATE] Destination mailbox does not exist",
            ))
        }
    };

    // Parse sequence set
    let message_ids = parse_sequence_set(sequence)?;

    if message_ids.is_empty() {
        return Ok(ImapResponse::ok(tag, "COPY completed (no messages)"));
    }

    // Copy messages to destination mailbox
    let copied_metadata = ctx
        .message_store
        .copy_messages(&message_ids, dest_mailbox_id)
        .await?;

    // Build COPYUID response (RFC 4315)
    // Format: [COPYUID <uidvalidity> <source-uids> <dest-uids>]
    if !copied_metadata.is_empty() {
        let source_uids: Vec<String> = message_ids.iter().map(|id| id.to_string()).collect();
        let dest_uids: Vec<String> = copied_metadata
            .iter()
            .map(|m| m.uid().to_string())
            .collect();

        let uid_validity = dest_mailbox_obj.map(|mb| mb.uid_validity()).unwrap_or(0);
        Ok(ImapResponse::ok(
            tag,
            format!(
                "[COPYUID {} {} {}] COPY completed",
                uid_validity,
                source_uids.join(","),
                dest_uids.join(",")
            ),
        ))
    } else {
        Ok(ImapResponse::ok(tag, "COPY completed"))
    }
}

/// Handle MOVE command (RFC 6851)
pub(crate) async fn handle_move(
    ctx: &HandlerContext,
    session: &ImapSession,
    tag: &str,
    sequence: &str,
    dest_mailbox: &str,
) -> anyhow::Result<ImapResponse> {
    // Must have a mailbox selected
    let _source_mailbox_id = match session.state() {
        ImapState::Selected { mailbox_id } => mailbox_id,
        _ => return Ok(ImapResponse::no(tag, "No mailbox selected")),
    };

    // Get username from session
    let username = match &session.username {
        Some(u) => u.clone(),
        None => return Ok(ImapResponse::no(tag, "No username in session")),
    };

    // Find the destination mailbox
    let mailboxes = ctx.mailbox_store.list_mailboxes(&username).await?;
    let dest_mailbox_obj = mailboxes
        .iter()
        .find(|m| m.path().name() == Some(dest_mailbox));

    let dest_mailbox_id = match dest_mailbox_obj {
        Some(mb) => mb.id(),
        None => {
            return Ok(ImapResponse::no(
                tag,
                "[TRYCREATE] Destination mailbox does not exist",
            ))
        }
    };

    // Parse sequence set
    let message_ids = parse_sequence_set(sequence)?;

    if message_ids.is_empty() {
        return Ok(ImapResponse::ok(tag, "MOVE completed (no messages)"));
    }

    // Copy messages to destination mailbox
    let copied_metadata = ctx
        .message_store
        .copy_messages(&message_ids, dest_mailbox_id)
        .await?;

    // Mark messages as deleted in source mailbox (implicit expunge for MOVE)
    let mut delete_flags = MessageFlags::new();
    delete_flags.set_deleted(true);
    ctx.message_store
        .set_flags(&message_ids, delete_flags)
        .await?;

    // Actually delete the messages from the source mailbox
    ctx.message_store.delete_messages(&message_ids).await?;

    // Build MOVEUID response (similar to COPYUID but for MOVE)
    // Format: [COPYUID <uidvalidity> <source-uids> <dest-uids>]
    // Note: RFC 6851 still uses COPYUID response code for MOVE
    if !copied_metadata.is_empty() {
        let source_uids: Vec<String> = message_ids.iter().map(|id| id.to_string()).collect();
        let dest_uids: Vec<String> = copied_metadata
            .iter()
            .map(|m| m.uid().to_string())
            .collect();

        let uid_validity = dest_mailbox_obj.map(|mb| mb.uid_validity()).unwrap_or(0);
        Ok(ImapResponse::ok(
            tag,
            format!(
                "[COPYUID {} {} {}] MOVE completed",
                uid_validity,
                source_uids.join(","),
                dest_uids.join(",")
            ),
        ))
    } else {
        Ok(ImapResponse::ok(tag, "MOVE completed"))
    }
}

/// Handle EXPUNGE command (RFC 9051 Section 6.4.3)
/// Permanently removes all messages with \Deleted flag from the selected mailbox
pub(crate) async fn handle_expunge(
    ctx: &HandlerContext,
    session: &ImapSession,
    tag: &str,
) -> anyhow::Result<ImapResponse> {
    // Must have a mailbox selected
    let mailbox_id = match session.state() {
        ImapState::Selected { mailbox_id } => mailbox_id,
        _ => return Ok(ImapResponse::no(tag, "No mailbox selected")),
    };

    // Get all messages in the mailbox
    let messages = ctx.message_store.get_mailbox_messages(mailbox_id).await?;

    // Find messages with \Deleted flag and collect their sequence numbers
    let mut deleted_messages = Vec::new();
    let mut expunge_responses = Vec::new();
    let mut expunge_seqs: Vec<u32> = Vec::new();

    for (seq_num, metadata) in messages.iter().enumerate() {
        if metadata.flags().is_deleted() {
            deleted_messages.push(*metadata.message_id());
            // IMAP sequence numbers are 1-based
            let seq = (seq_num + 1) as u32;
            expunge_responses.push(format!("* {} EXPUNGE", seq));
            expunge_seqs.push(seq);
        }
    }

    // Delete the messages from storage
    if !deleted_messages.is_empty() {
        ctx.message_store.delete_messages(&deleted_messages).await?;

        // Broadcast EXPUNGE events to all sessions watching this mailbox.
        for seq in &expunge_seqs {
            ctx.mailbox_registry
                .publish(*mailbox_id, MailboxEvent::Expunge { seq: *seq });
        }
    }

    // Build response with untagged EXPUNGE responses
    let mut full_response = expunge_responses.join("\r\n");
    if !full_response.is_empty() {
        full_response.push_str("\r\n");
    }
    full_response.push_str(&format!("{} OK EXPUNGE completed", tag));

    Ok(ImapResponse::new(None, "", full_response))
}

/// Handle CLOSE command (RFC 9051 Section 6.4.2)
/// Performs implicit EXPUNGE and then deselects the mailbox
pub(crate) async fn handle_close(
    ctx: &HandlerContext,
    session: &mut ImapSession,
    tag: &str,
) -> anyhow::Result<ImapResponse> {
    // Must have a mailbox selected
    let mailbox_id = match session.state() {
        ImapState::Selected { mailbox_id } => mailbox_id,
        _ => return Ok(ImapResponse::no(tag, "No mailbox selected")),
    };

    // Perform implicit expunge (delete messages with \Deleted flag)
    let messages = ctx.message_store.get_mailbox_messages(mailbox_id).await?;
    let deleted_messages: Vec<MessageId> = messages
        .iter()
        .filter(|m| m.flags().is_deleted())
        .map(|m| *m.message_id())
        .collect();

    if !deleted_messages.is_empty() {
        ctx.message_store.delete_messages(&deleted_messages).await?;
    }

    // Deselect mailbox - return to Authenticated state
    session.state = ImapState::Authenticated;
    // Drop the broadcast subscription — the mailbox is no longer selected.
    session.mailbox_event_rx = None;

    // CLOSE does not send untagged EXPUNGE responses (unlike EXPUNGE command)
    Ok(ImapResponse::ok(tag, "CLOSE completed"))
}

/// Handle UID command (RFC 9051 Section 6.4.8)
pub(crate) async fn handle_uid(
    ctx: &HandlerContext,
    session: &ImapSession,
    tag: &str,
    subcommand: &UidSubcommand,
) -> anyhow::Result<ImapResponse> {
    // All UID commands require Selected state
    match session.state() {
        ImapState::Selected { .. } => {}
        _ => return Ok(ImapResponse::no(tag, "No mailbox selected")),
    }

    match subcommand {
        UidSubcommand::Fetch { sequence, items } => {
            handle_uid_fetch(ctx, session, tag, sequence, items).await
        }
        UidSubcommand::Store {
            sequence,
            mode,
            flags,
        } => handle_uid_store(ctx, session, tag, sequence, mode.clone(), flags).await,
        UidSubcommand::Search { criteria } => handle_uid_search(ctx, session, tag, criteria).await,
        UidSubcommand::Copy { sequence, mailbox } => {
            handle_uid_copy(ctx, session, tag, sequence, mailbox).await
        }
        UidSubcommand::Move { sequence, mailbox } => {
            handle_uid_move(ctx, session, tag, sequence, mailbox).await
        }
        UidSubcommand::Expunge { sequence } => {
            handle_uid_expunge(ctx, session, tag, sequence).await
        }
    }
}

/// Handle UID FETCH command
async fn handle_uid_fetch(
    ctx: &HandlerContext,
    session: &ImapSession,
    tag: &str,
    uid_sequence: &str,
    items: &[String],
) -> anyhow::Result<ImapResponse> {
    // Must have a mailbox selected
    let mailbox_id = match session.state() {
        ImapState::Selected { mailbox_id } => mailbox_id,
        _ => return Ok(ImapResponse::no(tag, "No mailbox selected")),
    };

    // Get all messages in mailbox
    let all_metadata = ctx.message_store.get_mailbox_messages(mailbox_id).await?;

    // Parse UID sequence set and filter messages by UID
    let uid_set = parse_uid_sequence_set(uid_sequence, &all_metadata)?;
    let matching_metadata: Vec<_> = all_metadata
        .iter()
        .filter(|m| uid_set.contains(&m.uid()))
        .collect();

    // Fetch each message
    let mut responses = Vec::new();
    for (seq_num, metadata) in matching_metadata.iter().enumerate() {
        if let Some(mail) = ctx.message_store.get_message(metadata.message_id()).await? {
            // Build FETCH response based on requested items
            let fetch_items = build_fetch_items(&mail, metadata, items).await;
            // Include UID in response (already included in fetch_items if requested)
            // Sequence number is 1-based
            responses.push(format!("* {} FETCH ({})", seq_num + 1, fetch_items));
        }
    }

    // Combine responses
    let mut full_response = responses.join("\r\n");
    if !full_response.is_empty() {
        full_response.push_str("\r\n");
    }
    full_response.push_str(&format!("{} OK UID FETCH completed", tag));

    Ok(ImapResponse::new(None, "", full_response))
}

/// Handle UID STORE command
async fn handle_uid_store(
    ctx: &HandlerContext,
    session: &ImapSession,
    tag: &str,
    uid_sequence: &str,
    mode: StoreMode,
    flags: &[String],
) -> anyhow::Result<ImapResponse> {
    // Must have a mailbox selected
    let mailbox_id = match session.state() {
        ImapState::Selected { mailbox_id } => mailbox_id,
        _ => return Ok(ImapResponse::no(tag, "No mailbox selected")),
    };

    // Get all messages in mailbox
    let all_metadata = ctx.message_store.get_mailbox_messages(mailbox_id).await?;

    // Parse UID sequence set and filter messages by UID.
    // Capture both the MessageIds (for set_flags) and the UIDs (for broadcast)
    // from the SAME snapshot to avoid a fragile MessageId round-trip after
    // set_flags moves the file from new/ to cur/.
    let uid_set = parse_uid_sequence_set(uid_sequence, &all_metadata)?;
    let message_ids: Vec<MessageId> = all_metadata
        .iter()
        .filter(|m| uid_set.contains(&m.uid()))
        .map(|m| *m.message_id())
        .collect();
    // Capture UIDs now, before set_flags may relocate the files.
    let target_uids: Vec<u32> = all_metadata
        .iter()
        .filter(|m| uid_set.contains(&m.uid()))
        .map(|m| m.uid())
        .collect();

    if message_ids.is_empty() {
        return Ok(ImapResponse::ok(tag, "UID STORE completed (no messages)"));
    }

    // Build MessageFlags from string flags
    let msg_flags = build_message_flags(flags);

    // Apply flags based on mode
    match mode {
        StoreMode::Replace => {
            ctx.message_store.set_flags(&message_ids, msg_flags).await?;
        }
        StoreMode::Add => {
            // Would need to fetch current flags and merge
            ctx.message_store.set_flags(&message_ids, msg_flags).await?;
        }
        StoreMode::Remove => {
            // Would need to fetch current flags and remove
            ctx.message_store.set_flags(&message_ids, msg_flags).await?;
        }
    }

    // Broadcast FlagsChanged to all sessions watching this mailbox.
    // Use UIDs captured before set_flags to avoid a second get_mailbox_messages call
    // (set_flags moves files from new/ to cur/, which can change MessageId lookup reliability).
    let flag_strings: Vec<String> = flags.to_vec();
    for uid in target_uids {
        ctx.mailbox_registry.publish(
            *mailbox_id,
            MailboxEvent::FlagsChanged {
                uid,
                flags: flag_strings.clone(),
            },
        );
    }

    Ok(ImapResponse::ok(tag, "UID STORE completed"))
}

/// Handle UID SEARCH command
async fn handle_uid_search(
    ctx: &HandlerContext,
    session: &ImapSession,
    tag: &str,
    criteria: &[String],
) -> anyhow::Result<ImapResponse> {
    // Must have a mailbox selected
    let mailbox_id = match session.state() {
        ImapState::Selected { mailbox_id } => mailbox_id,
        _ => return Ok(ImapResponse::no(tag, "No mailbox selected")),
    };

    // Parse search criteria
    let search_criteria = parse_search_criteria(criteria);

    // Perform search to get message IDs
    let message_ids = ctx
        .message_store
        .search(mailbox_id, search_criteria)
        .await?;

    // Get all messages to map message IDs to UIDs
    let all_metadata = ctx.message_store.get_mailbox_messages(mailbox_id).await?;
    let uids: Vec<String> = all_metadata
        .iter()
        .filter(|m| message_ids.contains(m.message_id()))
        .map(|m| m.uid().to_string())
        .collect();

    // Build response with UIDs instead of sequence numbers
    let response = format!(
        "* SEARCH {}\r\n{} OK UID SEARCH completed",
        uids.join(" "),
        tag
    );

    Ok(ImapResponse::new(None, "", response))
}

/// Handle UID COPY command
async fn handle_uid_copy(
    ctx: &HandlerContext,
    session: &ImapSession,
    tag: &str,
    uid_sequence: &str,
    dest_mailbox: &str,
) -> anyhow::Result<ImapResponse> {
    // Must have a mailbox selected
    let source_mailbox_id = match session.state() {
        ImapState::Selected { mailbox_id } => mailbox_id,
        _ => return Ok(ImapResponse::no(tag, "No mailbox selected")),
    };

    // Get username from session
    let username = match &session.username {
        Some(u) => u.clone(),
        None => return Ok(ImapResponse::no(tag, "No username in session")),
    };

    // Find the destination mailbox
    let mailboxes = ctx.mailbox_store.list_mailboxes(&username).await?;
    let dest_mailbox_obj = mailboxes
        .iter()
        .find(|m| m.path().name() == Some(dest_mailbox));

    let dest_mailbox_id = match dest_mailbox_obj {
        Some(mb) => mb.id(),
        None => {
            return Ok(ImapResponse::no(
                tag,
                "[TRYCREATE] Destination mailbox does not exist",
            ))
        }
    };

    // Get all messages in source mailbox
    let all_metadata = ctx
        .message_store
        .get_mailbox_messages(source_mailbox_id)
        .await?;

    // Parse UID sequence set and filter messages by UID
    let uid_set = parse_uid_sequence_set(uid_sequence, &all_metadata)?;
    let message_ids: Vec<MessageId> = all_metadata
        .iter()
        .filter(|m| uid_set.contains(&m.uid()))
        .map(|m| *m.message_id())
        .collect();

    if message_ids.is_empty() {
        return Ok(ImapResponse::ok(tag, "UID COPY completed (no messages)"));
    }

    // Copy messages to destination mailbox
    let copied_metadata = ctx
        .message_store
        .copy_messages(&message_ids, dest_mailbox_id)
        .await?;

    // Build COPYUID response (RFC 4315)
    if !copied_metadata.is_empty() {
        let source_uids: Vec<String> = all_metadata
            .iter()
            .filter(|m| message_ids.contains(m.message_id()))
            .map(|m| m.uid().to_string())
            .collect();
        let dest_uids: Vec<String> = copied_metadata
            .iter()
            .map(|m| m.uid().to_string())
            .collect();

        let uid_validity = dest_mailbox_obj.map(|mb| mb.uid_validity()).unwrap_or(0);
        Ok(ImapResponse::ok(
            tag,
            format!(
                "[COPYUID {} {} {}] UID COPY completed",
                uid_validity,
                source_uids.join(","),
                dest_uids.join(",")
            ),
        ))
    } else {
        Ok(ImapResponse::ok(tag, "UID COPY completed"))
    }
}

/// Handle UID MOVE command
async fn handle_uid_move(
    ctx: &HandlerContext,
    session: &ImapSession,
    tag: &str,
    uid_sequence: &str,
    dest_mailbox: &str,
) -> anyhow::Result<ImapResponse> {
    // Must have a mailbox selected
    let source_mailbox_id = match session.state() {
        ImapState::Selected { mailbox_id } => mailbox_id,
        _ => return Ok(ImapResponse::no(tag, "No mailbox selected")),
    };

    // Get username from session
    let username = match &session.username {
        Some(u) => u.clone(),
        None => return Ok(ImapResponse::no(tag, "No username in session")),
    };

    // Find the destination mailbox
    let mailboxes = ctx.mailbox_store.list_mailboxes(&username).await?;
    let dest_mailbox_obj = mailboxes
        .iter()
        .find(|m| m.path().name() == Some(dest_mailbox));

    let dest_mailbox_id = match dest_mailbox_obj {
        Some(mb) => mb.id(),
        None => {
            return Ok(ImapResponse::no(
                tag,
                "[TRYCREATE] Destination mailbox does not exist",
            ))
        }
    };

    // Get all messages in source mailbox
    let all_metadata = ctx
        .message_store
        .get_mailbox_messages(source_mailbox_id)
        .await?;

    // Parse UID sequence set and filter messages by UID
    let uid_set = parse_uid_sequence_set(uid_sequence, &all_metadata)?;
    let message_ids: Vec<MessageId> = all_metadata
        .iter()
        .filter(|m| uid_set.contains(&m.uid()))
        .map(|m| *m.message_id())
        .collect();

    if message_ids.is_empty() {
        return Ok(ImapResponse::ok(tag, "UID MOVE completed (no messages)"));
    }

    // Copy messages to destination mailbox
    let copied_metadata = ctx
        .message_store
        .copy_messages(&message_ids, dest_mailbox_id)
        .await?;

    // Mark messages as deleted in source mailbox
    let mut delete_flags = MessageFlags::new();
    delete_flags.set_deleted(true);
    ctx.message_store
        .set_flags(&message_ids, delete_flags)
        .await?;

    // Actually delete the messages from the source mailbox
    ctx.message_store.delete_messages(&message_ids).await?;

    // Build COPYUID response (RFC 6851 uses COPYUID for MOVE)
    if !copied_metadata.is_empty() {
        let source_uids: Vec<String> = all_metadata
            .iter()
            .filter(|m| message_ids.contains(m.message_id()))
            .map(|m| m.uid().to_string())
            .collect();
        let dest_uids: Vec<String> = copied_metadata
            .iter()
            .map(|m| m.uid().to_string())
            .collect();

        let uid_validity = dest_mailbox_obj.map(|mb| mb.uid_validity()).unwrap_or(0);
        Ok(ImapResponse::ok(
            tag,
            format!(
                "[COPYUID {} {} {}] UID MOVE completed",
                uid_validity,
                source_uids.join(","),
                dest_uids.join(",")
            ),
        ))
    } else {
        Ok(ImapResponse::ok(tag, "UID MOVE completed"))
    }
}

/// Handle UID EXPUNGE command (RFC 4315)
/// Permanently removes messages with specified UIDs that have the \Deleted flag
async fn handle_uid_expunge(
    ctx: &HandlerContext,
    session: &ImapSession,
    tag: &str,
    uid_sequence: &str,
) -> anyhow::Result<ImapResponse> {
    // Must have a mailbox selected
    let mailbox_id = match session.state() {
        ImapState::Selected { mailbox_id } => mailbox_id,
        _ => return Ok(ImapResponse::no(tag, "No mailbox selected")),
    };

    // Get all messages in the mailbox
    let all_metadata = ctx.message_store.get_mailbox_messages(mailbox_id).await?;

    // Parse UID sequence set
    let uid_set = parse_uid_sequence_set(uid_sequence, &all_metadata)?;

    // Find messages matching UIDs that also have \Deleted flag
    let mut deleted_messages = Vec::new();
    let mut expunge_responses = Vec::new();
    let mut expunge_seqs: Vec<u32> = Vec::new();

    for (seq_num, metadata) in all_metadata.iter().enumerate() {
        if uid_set.contains(&metadata.uid()) && metadata.flags().is_deleted() {
            deleted_messages.push(*metadata.message_id());
            // IMAP sequence numbers are 1-based
            let seq = (seq_num + 1) as u32;
            expunge_responses.push(format!("* {} EXPUNGE", seq));
            expunge_seqs.push(seq);
        }
    }

    // Delete the messages from storage
    if !deleted_messages.is_empty() {
        ctx.message_store.delete_messages(&deleted_messages).await?;

        // Broadcast EXPUNGE events to all sessions watching this mailbox.
        for seq in &expunge_seqs {
            ctx.mailbox_registry
                .publish(*mailbox_id, MailboxEvent::Expunge { seq: *seq });
        }
    }

    // Build response with untagged EXPUNGE responses
    let mut full_response = expunge_responses.join("\r\n");
    if !full_response.is_empty() {
        full_response.push_str("\r\n");
    }
    full_response.push_str(&format!("{} OK UID EXPUNGE completed", tag));

    Ok(ImapResponse::new(None, "", full_response))
}

// ---- Helper functions ----

/// Parse sequence set (simplified implementation)
pub(crate) fn parse_sequence_set(sequence: &str) -> anyhow::Result<Vec<MessageId>> {
    // For now, just return empty vec as we don't have real message IDs
    // In a real implementation, this would parse "1", "1:5", "1,3,5", "1:*", etc.
    let _ = sequence;
    Ok(Vec::new())
}

/// Parse sequence numbers (e.g., "1", "1:5", "1,3,5", "1:*")
pub(crate) fn parse_sequence_numbers(sequence: &str, max: usize) -> anyhow::Result<Vec<usize>> {
    let mut numbers = Vec::new();

    for part in sequence.split(',') {
        let part = part.trim();
        if part.contains(':') {
            // Range (e.g., "1:5" or "1:*")
            let range_parts: Vec<&str> = part.split(':').collect();
            if range_parts.len() == 2 {
                let start = range_parts[0].parse::<usize>().unwrap_or(1);
                let end = if range_parts[1] == "*" {
                    max
                } else {
                    range_parts[1].parse::<usize>().unwrap_or(max)
                };

                for n in start..=end.min(max) {
                    if !numbers.contains(&n) {
                        numbers.push(n);
                    }
                }
            }
        } else if part == "*" {
            // Last message
            if max > 0 && !numbers.contains(&max) {
                numbers.push(max);
            }
        } else {
            // Single number
            if let Ok(n) = part.parse::<usize>() {
                if n > 0 && n <= max && !numbers.contains(&n) {
                    numbers.push(n);
                }
            }
        }
    }

    numbers.sort();
    Ok(numbers)
}

/// Build FETCH response items
pub(crate) async fn build_fetch_items(
    mail: &rusmes_proto::Mail,
    metadata: &MessageMetadata,
    items: &[String],
) -> String {
    let mut fetch_items = Vec::new();

    for item in items {
        match item.to_uppercase().as_str() {
            "FLAGS" => {
                // Build flags string from metadata
                let flags = metadata.flags();
                let mut flag_list = Vec::new();
                if flags.is_seen() {
                    flag_list.push("\\Seen");
                }
                if flags.is_answered() {
                    flag_list.push("\\Answered");
                }
                if flags.is_flagged() {
                    flag_list.push("\\Flagged");
                }
                if flags.is_deleted() {
                    flag_list.push("\\Deleted");
                }
                if flags.is_draft() {
                    flag_list.push("\\Draft");
                }
                fetch_items.push(format!("FLAGS ({})", flag_list.join(" ")));
            }
            "UID" => {
                fetch_items.push(format!("UID {}", metadata.uid()));
            }
            "BODY[]" | "BODY.PEEK[]" => {
                // Get full message body
                let message = mail.message();
                if let Ok(body_text) = message.extract_text().await {
                    let body_len = body_text.len();
                    fetch_items.push(format!("BODY[] {{{}}}\r\n{}", body_len, body_text));
                } else {
                    fetch_items.push("BODY[] {0}\r\n".to_string());
                }
            }
            "RFC822.SIZE" => {
                fetch_items.push(format!("RFC822.SIZE {}", metadata.size()));
            }
            _ => {
                // Unknown item, skip
            }
        }
    }

    fetch_items.join(" ")
}

/// Parse search criteria (simplified)
pub(crate) fn parse_search_criteria(criteria: &[String]) -> SearchCriteria {
    if criteria.is_empty() {
        return SearchCriteria::All;
    }

    // Handle simple criteria
    match criteria[0].to_uppercase().as_str() {
        "ALL" => SearchCriteria::All,
        "UNSEEN" => SearchCriteria::Unseen,
        "SEEN" => SearchCriteria::Seen,
        "FLAGGED" => SearchCriteria::Flagged,
        "UNFLAGGED" => SearchCriteria::Unflagged,
        "DELETED" => SearchCriteria::Deleted,
        "UNDELETED" => SearchCriteria::Undeleted,
        _ => SearchCriteria::All, // Default to all
    }
}

/// Build MessageFlags from string flags
fn build_message_flags(flags: &[String]) -> MessageFlags {
    let mut msg_flags = MessageFlags::new();
    for flag in flags {
        match flag.to_uppercase().as_str() {
            "\\SEEN" => msg_flags.set_seen(true),
            "\\ANSWERED" => msg_flags.set_answered(true),
            "\\FLAGGED" => msg_flags.set_flagged(true),
            "\\DELETED" => msg_flags.set_deleted(true),
            "\\DRAFT" => msg_flags.set_draft(true),
            custom => msg_flags.add_custom(custom.to_string()),
        }
    }
    msg_flags
}

/// Parse message data into headers and body
pub(crate) fn parse_message_data(
    data: &bytes::Bytes,
) -> anyhow::Result<(rusmes_proto::HeaderMap, bytes::Bytes)> {
    use rusmes_proto::HeaderMap;

    let data_str = String::from_utf8_lossy(data);
    let mut headers = HeaderMap::new();
    let mut body_start = 0;

    // Find the blank line separating headers from body
    let lines: Vec<&str> = data_str.split("\r\n").collect();
    let mut i = 0;

    while i < lines.len() {
        let line = lines[i];

        // Empty line marks end of headers
        if line.is_empty() {
            body_start = data_str[..data_str.len()]
                .find("\r\n\r\n")
                .map(|pos| pos + 4)
                .unwrap_or(data.len());
            break;
        }

        // Parse header line
        if let Some(colon_pos) = line.find(':') {
            let name = line[..colon_pos].trim();
            let value = line[colon_pos + 1..].trim();
            headers.insert(name.to_string(), value.to_string());
        }

        i += 1;
    }

    // Extract body
    let body = if body_start < data.len() {
        data.slice(body_start..)
    } else {
        bytes::Bytes::new()
    };

    Ok((headers, body))
}

/// Extract sender from message headers
pub(crate) fn extract_sender_from_headers(
    headers: &rusmes_proto::HeaderMap,
) -> Option<rusmes_proto::MailAddress> {
    if let Some(from) = headers.get_first("from") {
        // Simplified parsing - extract email from "Name <email@domain>" format
        let email = extract_email_address(from)?;
        parse_email_address(&email)
    } else {
        None
    }
}

/// Extract recipients from message headers
pub(crate) fn extract_recipients_from_headers(
    headers: &rusmes_proto::HeaderMap,
) -> Vec<rusmes_proto::MailAddress> {
    let mut recipients = Vec::new();

    // Parse To: header
    if let Some(to_values) = headers.get("to") {
        for to in to_values {
            if let Some(email) = extract_email_address(to) {
                if let Some(addr) = parse_email_address(&email) {
                    recipients.push(addr);
                }
            }
        }
    }

    // Parse Cc: header
    if let Some(cc_values) = headers.get("cc") {
        for cc in cc_values {
            if let Some(email) = extract_email_address(cc) {
                if let Some(addr) = parse_email_address(&email) {
                    recipients.push(addr);
                }
            }
        }
    }

    recipients
}

/// Extract email address from string like "Name <email@domain>" or "email@domain"
fn extract_email_address(s: &str) -> Option<String> {
    if let Some(start) = s.find('<') {
        if let Some(end) = s.find('>') {
            return Some(s[start + 1..end].trim().to_string());
        }
    }

    // No angle brackets, might be plain email
    let trimmed = s.trim();
    if trimmed.contains('@') {
        return Some(trimmed.to_string());
    }

    None
}

/// Parse email address string into MailAddress
fn parse_email_address(email: &str) -> Option<rusmes_proto::MailAddress> {
    use rusmes_proto::{Domain, MailAddress};

    if let Some(at_pos) = email.find('@') {
        let local_part = &email[..at_pos];
        let domain_str = &email[at_pos + 1..];

        if let Ok(domain) = Domain::new(domain_str.to_string()) {
            if let Ok(addr) = MailAddress::new(local_part, domain) {
                return Some(addr);
            }
        }
    }

    None
}

/// Parse UID sequence set into a set of UIDs
/// Supports formats like "1", "1:5", "1,3,5", "1:*", "*"
fn parse_uid_sequence_set(
    sequence: &str,
    all_metadata: &[MessageMetadata],
) -> anyhow::Result<std::collections::HashSet<u32>> {
    use std::collections::HashSet;

    let mut uid_set = HashSet::new();

    // Find max UID for handling "*"
    let max_uid = all_metadata.iter().map(|m| m.uid()).max().unwrap_or(0);

    // Split by comma for multiple ranges/values
    for part in sequence.split(',') {
        let part = part.trim();

        if part.contains(':') {
            // Range specification
            let range_parts: Vec<&str> = part.split(':').collect();
            if range_parts.len() != 2 {
                return Err(anyhow::anyhow!("Invalid UID range: {}", part));
            }

            let start = if range_parts[0] == "*" {
                max_uid
            } else {
                range_parts[0].parse::<u32>()?
            };

            let end = if range_parts[1] == "*" {
                max_uid
            } else {
                range_parts[1].parse::<u32>()?
            };

            // Add all UIDs in range
            for uid in start..=end {
                uid_set.insert(uid);
            }
        } else {
            // Single UID
            let uid = if part == "*" {
                max_uid
            } else {
                part.parse::<u32>()?
            };
            uid_set.insert(uid);
        }
    }

    Ok(uid_set)
}