repartee 0.9.1

A modern terminal IRC client built with Ratatui and Tokio
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
// IRCv3 `batch` extension — collects messages within a BATCH and processes them as a group.
//
// Server sends:
//   BATCH +ref_tag batch_type [params...]  — start a batch
//   messages with @batch=ref_tag tag       — messages within the batch
//   BATCH -ref_tag                         — end the batch
//
// NETSPLIT/NETJOIN batch types produce summary messages instead of individual
// QUIT/JOIN events, providing server-authoritative netsplit information.

use std::collections::{HashMap, HashSet};
use std::time::Instant;

use irc::proto::{Command, Message as IrcMessage};

use crate::irc::formatting::{extract_nick, extract_nick_userhost};
use crate::state::AppState;
use crate::state::buffer::{Message, MessageType, NickEntry, make_buffer_id};

/// Maximum number of nicks to show in a netsplit/netjoin summary line.
const MAX_NICKS_DISPLAY: usize = 15;

/// Maximum time a batch can remain open before being discarded (60 seconds).
const BATCH_TIMEOUT_SECS: u64 = 60;

/// Information about an in-progress batch.
#[derive(Debug, Clone)]
pub struct BatchInfo {
    /// The batch type (e.g. "NETSPLIT", "NETJOIN", or a vendor extension).
    pub batch_type: String,
    /// Additional parameters from the BATCH start line.
    pub params: Vec<String>,
    /// Messages collected while the batch was open.
    pub messages: Vec<IrcMessage>,
    /// When this batch was opened.
    pub started_at: Instant,
}

/// Tracks open `IRCv3` batches for a single connection.
#[derive(Debug, Default)]
pub struct BatchTracker {
    /// Open batches keyed by reference tag.
    open: HashMap<String, BatchInfo>,
}

impl BatchTracker {
    /// Start a new batch with the given reference tag, type, and parameters.
    pub fn start_batch(&mut self, ref_tag: &str, batch_type: &str, params: Vec<String>) {
        self.open.insert(
            ref_tag.to_string(),
            BatchInfo {
                batch_type: batch_type.to_uppercase(),
                params,
                messages: Vec::new(),
                started_at: Instant::now(),
            },
        );
    }

    /// Remove batches that have been open longer than `BATCH_TIMEOUT_SECS`.
    ///
    /// Returns the number of expired batches discarded. Should be called
    /// periodically (e.g. once per second from the main tick).
    pub fn purge_expired(&mut self) -> usize {
        let timeout = std::time::Duration::from_secs(BATCH_TIMEOUT_SECS);
        let before = self.open.len();
        self.open.retain(|tag, info| {
            let expired = info.started_at.elapsed() >= timeout;
            if expired {
                tracing::warn!(
                    "discarding expired batch tag={tag} type={} msgs={}",
                    info.batch_type,
                    info.messages.len()
                );
            }
            !expired
        });
        before - self.open.len()
    }

    /// Check whether a message belongs to an open batch via its `@batch` tag.
    #[must_use]
    pub fn is_batched(&self, msg: &IrcMessage) -> bool {
        Self::get_batch_tag(msg).is_some_and(|tag| self.open.contains_key(tag))
    }

    /// Add a message to its batch (identified by the `@batch` tag).
    ///
    /// Returns `true` if the message was added to a batch, `false` if no
    /// matching open batch was found.
    pub fn add_message(&mut self, msg: IrcMessage) -> bool {
        let Some(tag) = Self::get_batch_tag_owned(&msg) else {
            return false;
        };
        if let Some(info) = self.open.get_mut(&tag) {
            info.messages.push(msg);
            true
        } else {
            false
        }
    }

    /// End a batch and return its collected information.
    ///
    /// Returns `None` if no batch with the given tag exists.
    pub fn end_batch(&mut self, ref_tag: &str) -> Option<BatchInfo> {
        self.open.remove(ref_tag)
    }

    /// Extract the `@batch` tag value from a message, returning a reference
    /// to the tag string within the message's tag list.
    fn get_batch_tag(msg: &IrcMessage) -> Option<&str> {
        msg.tags.as_ref().and_then(|tags| {
            tags.iter()
                .find(|t| t.0 == "batch")
                .and_then(|t| t.1.as_deref())
        })
    }

    /// Same as `get_batch_tag` but returns an owned `String`.
    fn get_batch_tag_owned(msg: &IrcMessage) -> Option<String> {
        Self::get_batch_tag(msg).map(str::to_string)
    }
}

/// Process a completed batch, generating appropriate state changes and messages.
///
/// - NETSPLIT: Produces a single summary line instead of individual QUIT messages.
/// - NETJOIN: Produces a single summary line instead of individual JOIN messages.
/// - Other batch types: Messages are replayed through the normal handler.
pub fn process_completed_batch(state: &mut AppState, conn_id: &str, batch: &BatchInfo) {
    match batch.batch_type.as_str() {
        "NETSPLIT" => process_netsplit_batch(state, conn_id, batch),
        "NETJOIN" => process_netjoin_batch(state, conn_id, batch),
        _ => {
            // Unknown batch type — replay messages through the normal handler.
            for msg in &batch.messages {
                crate::irc::events::handle_irc_message(state, conn_id, msg);
            }
        }
    }
}

/// Process a NETSPLIT batch: remove nicks from channels and produce a summary.
///
/// NETSPLIT batch params: `[server1, server2]`
/// Batch contains QUIT messages from users affected by the split.
fn process_netsplit_batch(state: &mut AppState, conn_id: &str, batch: &BatchInfo) {
    let server1 = batch.params.first().map_or("???", String::as_str);
    let server2 = batch.params.get(1).map_or("???", String::as_str);

    let mut nicks: Vec<String> = Vec::new();
    let mut nick_seen: HashSet<String> = HashSet::new();
    let mut affected_buffers: HashMap<String, Vec<String>> = HashMap::new();

    for msg in &batch.messages {
        if let Command::QUIT(_) = &msg.command {
            let Some(nick) = extract_nick(msg.prefix.as_ref()) else {
                continue;
            };

            // Find all buffers this nick is in on this connection.
            // Nick HashMap keys are always lowercase (case-insensitive IRC nicks).
            let nick_lower = nick.to_lowercase();
            let shared: Vec<String> = state
                .buffers
                .iter()
                .filter(|(_, buf)| {
                    buf.connection_id == conn_id && buf.users.contains_key(&nick_lower)
                })
                .map(|(id, _)| id.clone())
                .collect();

            // Remove nick from all buffers
            for buf_id in &shared {
                state.remove_nick(buf_id, &nick_lower);
                affected_buffers
                    .entry(buf_id.clone())
                    .or_default()
                    .push(nick.clone());
            }

            if nick_seen.insert(nick.clone()) {
                nicks.push(nick);
            }
        }
    }

    if nicks.is_empty() {
        return;
    }

    let nick_str = format_nick_list(&nicks);
    let text = format!("Netsplit {server1} \u{21C4} {server2} quits: {nick_str}");

    // Post the summary message to each affected buffer
    let ts = chrono::Utc::now();
    for buf_id in affected_buffers.keys() {
        let id = state.next_message_id();
        state.add_message(
            buf_id,
            Message {
                id,
                timestamp: ts,
                message_type: MessageType::Event,
                nick: None,
                nick_mode: None,
                text: text.clone(),
                highlight: false,
                event_key: Some("netsplit".to_string()),
                event_params: Some(vec![server1.to_string(), server2.to_string()]),
                log_msg_id: None,
                log_ref_id: None,
                tags: None,
            },
        );
    }
}

/// Process a NETJOIN batch: add nicks back to channels and produce a summary.
///
/// NETJOIN batch params: `[server1, server2]`
/// Batch contains JOIN messages from users rejoining after a split.
fn process_netjoin_batch(state: &mut AppState, conn_id: &str, batch: &BatchInfo) {
    let server1 = batch.params.first().map_or("???", String::as_str);
    let server2 = batch.params.get(1).map_or("???", String::as_str);

    let mut nicks: Vec<String> = Vec::new();
    let mut nick_seen: HashSet<String> = HashSet::new();
    let mut affected_buffers: HashMap<String, bool> = HashMap::new();

    // Directly update nick lists without replaying through handle_irc_message,
    // which would generate individual join display messages we don't want.
    for msg in &batch.messages {
        if let Command::JOIN(channel, account, _) = &msg.command {
            let (nick, _ident, _host) = extract_nick_userhost(msg.prefix.as_ref());
            let buffer_id = make_buffer_id(conn_id, channel);

            // Parse account from extended-join parameter
            let account = match account.as_deref() {
                Some("*") | None => None,
                Some(a) => Some(a.to_string()),
            };

            // Add nick directly to buffer's user list (state mutation only, no message)
            state.add_nick(
                &buffer_id,
                NickEntry {
                    nick: nick.clone(),
                    prefix: String::new(),
                    modes: String::new(),
                    away: false,
                    account,
                    ident: None,
                    host: None,
                },
            );

            affected_buffers.insert(buffer_id, true);
            if nick_seen.insert(nick.clone()) {
                nicks.push(nick);
            }
        }
    }

    if nicks.is_empty() {
        return;
    }

    let nick_str = format_nick_list(&nicks);
    let text = format!("Netsplit over {server1} \u{21C4} {server2} joins: {nick_str}");

    let ts = chrono::Utc::now();
    for buf_id in affected_buffers.keys() {
        let id = state.next_message_id();
        state.add_message(
            buf_id,
            Message {
                id,
                timestamp: ts,
                message_type: MessageType::Event,
                nick: None,
                nick_mode: None,
                text: text.clone(),
                highlight: false,
                event_key: Some("netjoin".to_string()),
                event_params: Some(vec![server1.to_string(), server2.to_string()]),
                log_msg_id: None,
                log_ref_id: None,
                tags: None,
            },
        );
    }
}

/// Format a list of nicks for display, truncating with "(+N more)" if needed.
fn format_nick_list(nicks: &[String]) -> String {
    if nicks.len() > MAX_NICKS_DISPLAY {
        let shown: Vec<&str> = nicks[..MAX_NICKS_DISPLAY]
            .iter()
            .map(String::as_str)
            .collect();
        let more = nicks.len() - MAX_NICKS_DISPLAY;
        format!("{} (+{more} more)", shown.join(", "))
    } else {
        let refs: Vec<&str> = nicks.iter().map(String::as_str).collect();
        refs.join(", ")
    }
}

/// Check whether the `batch` capability is enabled for a connection.
#[must_use]
#[allow(dead_code)] // Will be used when netsplit heuristic bypass is wired
pub fn has_batch_cap(state: &AppState, conn_id: &str) -> bool {
    state
        .connections
        .get(conn_id)
        .is_some_and(|c| c.enabled_caps.contains("batch"))
}

// === Tests ===

#[cfg(test)]
mod tests {
    use super::*;
    use irc::proto::message::Tag;

    /// Helper to create an `IrcMessage` with a `@batch` tag.
    fn make_batched_message(batch_tag: &str, command: Command) -> IrcMessage {
        IrcMessage {
            tags: Some(vec![Tag("batch".to_string(), Some(batch_tag.to_string()))]),
            prefix: None,
            command,
        }
    }

    /// Helper to create an `IrcMessage` without tags.
    fn make_plain_message(command: Command) -> IrcMessage {
        IrcMessage {
            tags: None,
            prefix: None,
            command,
        }
    }

    /// Helper to create a QUIT message with a prefix and `@batch` tag.
    fn make_quit_msg(nick: &str, reason: &str, batch_tag: &str) -> IrcMessage {
        IrcMessage {
            tags: Some(vec![Tag("batch".to_string(), Some(batch_tag.to_string()))]),
            prefix: Some(irc::proto::Prefix::Nickname(
                nick.to_string(),
                "user".to_string(),
                "host.net".to_string(),
            )),
            command: Command::QUIT(Some(reason.to_string())),
        }
    }

    /// Helper to create a JOIN message with a prefix and `@batch` tag.
    #[allow(dead_code)]
    fn make_join_msg(nick: &str, channel: &str, batch_tag: &str) -> IrcMessage {
        IrcMessage {
            tags: Some(vec![Tag("batch".to_string(), Some(batch_tag.to_string()))]),
            prefix: Some(irc::proto::Prefix::Nickname(
                nick.to_string(),
                "user".to_string(),
                "host.net".to_string(),
            )),
            command: Command::JOIN(channel.to_string(), None, None),
        }
    }

    fn make_test_server_config() -> crate::config::ServerConfig {
        crate::config::ServerConfig {
            label: "Test".to_string(),
            address: "irc.test.net".to_string(),
            port: 6697,
            tls: true,
            tls_verify: true,
            nick: None,
            username: None,
            realname: None,
            password: None,
            sasl_user: None,
            sasl_pass: None,
            bind_ip: None,
            channels: vec!["#test".to_string()],
            encoding: None,
            autoconnect: false,
            auto_reconnect: None,
            reconnect_delay: None,
            reconnect_max_retries: None,
            autosendcmd: None,
            sasl_mechanism: None,
            client_cert_path: None,
        }
    }

    #[test]
    fn start_and_end_batch_collects_messages() {
        let mut tracker = BatchTracker::default();
        tracker.start_batch("abc", "NETSPLIT", vec!["s1.net".into(), "s2.net".into()]);

        let msg1 = make_batched_message("abc", Command::QUIT(Some("split".to_string())));
        let msg2 = make_batched_message("abc", Command::QUIT(Some("split".to_string())));

        assert!(tracker.add_message(msg1));
        assert!(tracker.add_message(msg2));

        let batch = tracker.end_batch("abc").expect("batch should exist");
        assert_eq!(batch.batch_type, "NETSPLIT");
        assert_eq!(batch.params, vec!["s1.net", "s2.net"]);
        assert_eq!(batch.messages.len(), 2);
    }

    #[test]
    fn is_batched_detects_batch_tag() {
        let mut tracker = BatchTracker::default();
        tracker.start_batch("ref1", "NETSPLIT", vec![]);

        let batched = make_batched_message("ref1", Command::QUIT(None));
        let unbatched = make_plain_message(Command::QUIT(None));
        let wrong_tag = make_batched_message("ref2", Command::QUIT(None));

        assert!(tracker.is_batched(&batched));
        assert!(!tracker.is_batched(&unbatched));
        assert!(!tracker.is_batched(&wrong_tag));
    }

    #[test]
    fn end_nonexistent_batch_returns_none() {
        let mut tracker = BatchTracker::default();
        assert!(tracker.end_batch("nonexistent").is_none());
    }

    #[test]
    fn add_message_returns_false_for_unbatched() {
        let mut tracker = BatchTracker::default();
        let msg = make_plain_message(Command::PRIVMSG("#test".into(), "hello".into()));
        assert!(!tracker.add_message(msg));
    }

    #[test]
    fn add_message_returns_false_for_unknown_batch() {
        let mut tracker = BatchTracker::default();
        let msg = make_batched_message("unknown", Command::QUIT(None));
        assert!(!tracker.add_message(msg));
    }

    #[test]
    fn netsplit_batch_produces_summary() {
        let mut state = AppState::new();
        let conn_id = "test";

        // Set up connection and channel buffer with users
        state.add_connection(crate::state::connection::Connection {
            id: conn_id.to_string(),
            label: "Test".to_string(),
            status: crate::state::connection::ConnectionStatus::Connected,
            nick: "me".to_string(),
            user_modes: String::new(),
            isupport: HashMap::new(),
            isupport_parsed: crate::irc::isupport::Isupport::new(),
            error: None,
            lag: None,
            lag_pending: false,
            reconnect_attempts: 0,
            reconnect_delay_secs: 30,
            next_reconnect: None,
            should_reconnect: true,
            joined_channels: vec!["#test".to_string()],
            origin_config: make_test_server_config(),
            enabled_caps: std::collections::HashSet::new(),
            who_token_counter: 0,
            local_ip: None,
            silent_who_channels: std::collections::HashSet::new(),
        });

        let buf_id = make_buffer_id(conn_id, "#test");
        state.add_buffer(crate::state::buffer::Buffer {
            id: buf_id.clone(),
            connection_id: conn_id.to_string(),
            buffer_type: crate::state::buffer::BufferType::Channel,
            name: "#test".to_string(),
            messages: std::collections::VecDeque::new(),
            activity: crate::state::buffer::ActivityLevel::None,
            unread_count: 0,
            last_read: chrono::Utc::now(),
            topic: None,
            topic_set_by: None,
            users: HashMap::new(),
            modes: None,
            mode_params: None,
            list_modes: HashMap::new(),
            last_speakers: Vec::new(),
            peer_handle: None,
        });

        // Add users to the channel
        state.add_nick(
            &buf_id,
            crate::state::buffer::NickEntry {
                nick: "alice".to_string(),
                prefix: String::new(),
                modes: String::new(),
                away: false,
                account: None,
                ident: None,
                host: None,
            },
        );
        state.add_nick(
            &buf_id,
            crate::state::buffer::NickEntry {
                nick: "bob".to_string(),
                prefix: String::new(),
                modes: String::new(),
                away: false,
                account: None,
                ident: None,
                host: None,
            },
        );

        // Create NETSPLIT batch
        let batch = BatchInfo {
            batch_type: "NETSPLIT".to_string(),
            params: vec!["hub.net".to_string(), "leaf.net".to_string()],
            started_at: Instant::now(),
            messages: vec![
                make_quit_msg("alice", "hub.net leaf.net", "ref1"),
                make_quit_msg("bob", "hub.net leaf.net", "ref1"),
            ],
        };

        process_completed_batch(&mut state, conn_id, &batch);

        // Nicks should be removed from the buffer
        let buf = state.buffers.get(&buf_id).expect("buffer should exist");
        assert!(!buf.users.contains_key("alice"));
        assert!(!buf.users.contains_key("bob"));

        // A summary message should be added
        assert!(!buf.messages.is_empty());
        let last_msg = buf.messages.back().unwrap();
        assert!(last_msg.text.contains("Netsplit"));
        assert!(last_msg.text.contains("hub.net"));
        assert!(last_msg.text.contains("leaf.net"));
        assert!(last_msg.text.contains("alice"));
        assert!(last_msg.text.contains("bob"));
        assert!(last_msg.text.contains("quits:"));
    }

    #[test]
    fn messages_without_batch_tag_are_not_batched() {
        let mut tracker = BatchTracker::default();
        tracker.start_batch("ref1", "NETSPLIT", vec![]);

        let msg = make_plain_message(Command::PRIVMSG("#test".into(), "hello".into()));
        assert!(!tracker.is_batched(&msg));
        assert!(!tracker.add_message(msg));
    }

    #[test]
    fn multiple_batches_tracked_independently() {
        let mut tracker = BatchTracker::default();
        tracker.start_batch("aaa", "NETSPLIT", vec![]);
        tracker.start_batch("bbb", "NETJOIN", vec![]);

        let msg_a = make_batched_message("aaa", Command::QUIT(None));
        let msg_b = make_batched_message("bbb", Command::JOIN("#test".into(), None, None));

        assert!(tracker.add_message(msg_a));
        assert!(tracker.add_message(msg_b));

        let batch_a = tracker.end_batch("aaa").expect("batch aaa");
        assert_eq!(batch_a.batch_type, "NETSPLIT");
        assert_eq!(batch_a.messages.len(), 1);

        let batch_b = tracker.end_batch("bbb").expect("batch bbb");
        assert_eq!(batch_b.batch_type, "NETJOIN");
        assert_eq!(batch_b.messages.len(), 1);
    }

    #[test]
    fn format_nick_list_under_limit() {
        let nicks: Vec<String> = vec!["alice", "bob", "charlie"]
            .into_iter()
            .map(String::from)
            .collect();
        assert_eq!(format_nick_list(&nicks), "alice, bob, charlie");
    }

    #[test]
    fn format_nick_list_over_limit() {
        let nicks: Vec<String> = (0..20).map(|i| format!("nick{i}")).collect();
        let result = format_nick_list(&nicks);
        assert!(result.contains("(+5 more)"));
        assert!(result.contains("nick0"));
        assert!(result.contains("nick14"));
        assert!(!result.contains("nick15"));
    }

    #[test]
    fn batch_type_case_normalized() {
        let mut tracker = BatchTracker::default();
        tracker.start_batch("ref1", "netsplit", vec![]);

        let batch = tracker.end_batch("ref1").expect("batch should exist");
        assert_eq!(batch.batch_type, "NETSPLIT");
    }

    #[test]
    fn purge_expired_removes_old_batches() {
        let mut tracker = BatchTracker::default();
        // Manually insert a batch with an old timestamp
        tracker.open.insert(
            "old".to_string(),
            BatchInfo {
                batch_type: "NETSPLIT".to_string(),
                params: vec![],
                messages: vec![],
                started_at: Instant::now()
                    .checked_sub(std::time::Duration::from_secs(120))
                    .unwrap(),
            },
        );
        // Fresh batch should survive
        tracker.start_batch("fresh", "NETJOIN", vec![]);

        let purged = tracker.purge_expired();
        assert_eq!(purged, 1);
        assert!(tracker.end_batch("old").is_none());
        assert!(tracker.end_batch("fresh").is_some());
    }

    #[test]
    fn purge_expired_keeps_fresh_batches() {
        let mut tracker = BatchTracker::default();
        tracker.start_batch("a", "NETSPLIT", vec![]);
        tracker.start_batch("b", "NETJOIN", vec![]);

        let purged = tracker.purge_expired();
        assert_eq!(purged, 0);
        assert_eq!(tracker.open.len(), 2);
    }

    #[test]
    fn netsplit_batch_removes_nicks_case_insensitive() {
        let mut state = AppState::new();
        let conn_id = "test";

        state.add_connection(crate::state::connection::Connection {
            id: conn_id.to_string(),
            label: "Test".to_string(),
            status: crate::state::connection::ConnectionStatus::Connected,
            nick: "me".to_string(),
            user_modes: String::new(),
            isupport: HashMap::new(),
            isupport_parsed: crate::irc::isupport::Isupport::new(),
            error: None,
            lag: None,
            lag_pending: false,
            reconnect_attempts: 0,
            reconnect_delay_secs: 30,
            next_reconnect: None,
            should_reconnect: true,
            joined_channels: vec!["#test".to_string()],
            origin_config: make_test_server_config(),
            enabled_caps: std::collections::HashSet::new(),
            who_token_counter: 0,
            local_ip: None,
            silent_who_channels: std::collections::HashSet::new(),
        });

        let buf_id = make_buffer_id(conn_id, "#test");
        state.add_buffer(crate::state::buffer::Buffer {
            id: buf_id.clone(),
            connection_id: conn_id.to_string(),
            buffer_type: crate::state::buffer::BufferType::Channel,
            name: "#test".to_string(),
            messages: std::collections::VecDeque::new(),
            activity: crate::state::buffer::ActivityLevel::None,
            unread_count: 0,
            last_read: chrono::Utc::now(),
            topic: None,
            topic_set_by: None,
            users: HashMap::new(),
            modes: None,
            mode_params: None,
            list_modes: HashMap::new(),
            last_speakers: Vec::new(),
            peer_handle: None,
        });

        // Add users — add_nick stores keys as lowercase
        state.add_nick(
            &buf_id,
            NickEntry {
                nick: "Alice".to_string(),
                prefix: String::new(),
                modes: String::new(),
                away: false,
                account: None,
                ident: None,
                host: None,
            },
        );
        state.add_nick(
            &buf_id,
            NickEntry {
                nick: "BOB".to_string(),
                prefix: String::new(),
                modes: String::new(),
                away: false,
                account: None,
                ident: None,
                host: None,
            },
        );

        // QUIT messages use mixed-case nicks (as received from IRC)
        let batch = BatchInfo {
            batch_type: "NETSPLIT".to_string(),
            params: vec!["hub.net".to_string(), "leaf.net".to_string()],
            started_at: Instant::now(),
            messages: vec![
                make_quit_msg("Alice", "hub.net leaf.net", "ref1"),
                make_quit_msg("BOB", "hub.net leaf.net", "ref1"),
            ],
        };

        process_completed_batch(&mut state, conn_id, &batch);

        // Nicks should be removed despite case mismatch between IRC prefix and HashMap key
        let buf = state.buffers.get(&buf_id).expect("buffer should exist");
        assert!(!buf.users.contains_key("alice"), "alice should be removed");
        assert!(!buf.users.contains_key("bob"), "bob should be removed");
        assert_eq!(buf.users.len(), 0, "all users should be removed");

        // Summary message should still be present
        assert!(!buf.messages.is_empty());
        let last_msg = buf.messages.back().unwrap();
        assert!(last_msg.text.contains("Netsplit"));
        assert!(last_msg.text.contains("Alice"));
        assert!(last_msg.text.contains("BOB"));
    }
}