siggy 1.8.0

Terminal-based Signal messenger client with vim keybindings
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
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
//! SQLite persistence layer (WAL mode).
//!
//! Three core tables: `conversations`, `messages`, `read_markers`. Schema
//! migrations are version-based (see private `migrate`). Read paths
//! propagate errors via `?`; write paths are logged via
//! [`crate::conversation_store::db_warn`] (silent) or
//! `App::db_warn_visible` (surfaces in the status bar) so transient
//! persistence failures don't break the UI.

use std::collections::HashMap;
use std::path::Path;

use anyhow::Result;
use chrono::{DateTime, Utc};
use rusqlite::{Connection, params};

use crate::app::{Conversation, DisplayMessage};
use crate::mute::MuteState;
use crate::signal::types::{LinkPreview, Mention, MessageStatus, PollData, PollVote, Reaction};

/// (sender, body, timestamp_ms, conversation_id, conversation_name)
pub type SearchRow = (String, String, i64, String, String);

/// A schema migration: the target version it brings the database up to, and
/// the SQL batch that performs the change. Each batch is responsible for its
/// own `BEGIN; ...; UPDATE/INSERT schema_version; COMMIT;` so we never have to
/// template SQL strings at runtime.
struct Migration {
    version: i32,
    sql: &'static str,
}

/// Ordered list of schema migrations. To add a new version, append a new
/// `Migration` with the next version number and the SQL batch that lifts the
/// schema from `version - 1` to `version`. The batch must end with
/// `UPDATE schema_version SET version = N;` (or, for version 1, the initial
/// `INSERT`). Never edit an existing migration -- write a new one.
const MIGRATIONS: &[Migration] = &[
    Migration {
        version: 1,
        sql: "
            BEGIN;

            CREATE TABLE conversations (
                id         TEXT PRIMARY KEY,
                name       TEXT NOT NULL,
                is_group   INTEGER NOT NULL DEFAULT 0,
                created_at TEXT NOT NULL DEFAULT (datetime('now'))
            );

            CREATE TABLE messages (
                rowid           INTEGER PRIMARY KEY AUTOINCREMENT,
                conversation_id TEXT NOT NULL REFERENCES conversations(id),
                sender          TEXT NOT NULL,
                timestamp       TEXT NOT NULL,
                body            TEXT NOT NULL,
                is_system       INTEGER NOT NULL DEFAULT 0
            );
            CREATE INDEX idx_messages_conv_ts ON messages(conversation_id, timestamp);

            CREATE TABLE read_markers (
                conversation_id TEXT PRIMARY KEY REFERENCES conversations(id),
                last_read_rowid INTEGER NOT NULL DEFAULT 0
            );

            INSERT INTO schema_version (version) VALUES (1);

            COMMIT;
        ",
    },
    Migration {
        version: 2,
        sql: "
            BEGIN;
            ALTER TABLE conversations ADD COLUMN muted INTEGER NOT NULL DEFAULT 0;
            UPDATE schema_version SET version = 2;
            COMMIT;
        ",
    },
    Migration {
        version: 3,
        sql: "
            BEGIN;
            ALTER TABLE messages ADD COLUMN status INTEGER NOT NULL DEFAULT 0;
            ALTER TABLE messages ADD COLUMN timestamp_ms INTEGER NOT NULL DEFAULT 0;
            UPDATE schema_version SET version = 3;
            COMMIT;
        ",
    },
    Migration {
        version: 4,
        sql: "
            BEGIN;
            CREATE TABLE reactions (
                rowid           INTEGER PRIMARY KEY AUTOINCREMENT,
                conversation_id TEXT NOT NULL,
                target_ts_ms    INTEGER NOT NULL,
                target_author   TEXT NOT NULL,
                emoji           TEXT NOT NULL,
                sender          TEXT NOT NULL,
                UNIQUE(conversation_id, target_ts_ms, target_author, sender)
            );
            CREATE INDEX idx_reactions_target ON reactions(conversation_id, target_ts_ms);
            UPDATE schema_version SET version = 4;
            COMMIT;
        ",
    },
    Migration {
        version: 5,
        sql: "
            BEGIN;
            CREATE INDEX IF NOT EXISTS idx_messages_conv_ts_ms ON messages(conversation_id, timestamp_ms);
            UPDATE schema_version SET version = 5;
            COMMIT;
        ",
    },
    Migration {
        version: 6,
        sql: "
            BEGIN;
            ALTER TABLE messages ADD COLUMN is_edited INTEGER NOT NULL DEFAULT 0;
            ALTER TABLE messages ADD COLUMN is_deleted INTEGER NOT NULL DEFAULT 0;
            ALTER TABLE messages ADD COLUMN quote_author TEXT;
            ALTER TABLE messages ADD COLUMN quote_body TEXT;
            ALTER TABLE messages ADD COLUMN quote_ts_ms INTEGER;
            ALTER TABLE messages ADD COLUMN sender_id TEXT NOT NULL DEFAULT '';
            UPDATE schema_version SET version = 6;
            COMMIT;
        ",
    },
    Migration {
        version: 7,
        sql: "
            BEGIN;
            ALTER TABLE conversations ADD COLUMN expiration_timer INTEGER NOT NULL DEFAULT 0;
            ALTER TABLE messages ADD COLUMN expires_in_seconds INTEGER NOT NULL DEFAULT 0;
            ALTER TABLE messages ADD COLUMN expiration_start_ms INTEGER NOT NULL DEFAULT 0;
            UPDATE schema_version SET version = 7;
            COMMIT;
        ",
    },
    Migration {
        version: 8,
        sql: "
            BEGIN;
            ALTER TABLE conversations ADD COLUMN accepted INTEGER NOT NULL DEFAULT 1;
            UPDATE schema_version SET version = 8;
            COMMIT;
        ",
    },
    Migration {
        version: 9,
        sql: "
            BEGIN;
            ALTER TABLE conversations ADD COLUMN blocked INTEGER NOT NULL DEFAULT 0;
            UPDATE schema_version SET version = 9;
            COMMIT;
        ",
    },
    Migration {
        version: 10,
        sql: "
            BEGIN;
            ALTER TABLE messages ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0;
            UPDATE schema_version SET version = 10;
            COMMIT;
        ",
    },
    Migration {
        version: 11,
        sql: "
            BEGIN;
            ALTER TABLE messages ADD COLUMN poll_data TEXT;
            CREATE TABLE IF NOT EXISTS poll_votes (
                conv_id TEXT NOT NULL,
                poll_timestamp INTEGER NOT NULL,
                voter TEXT NOT NULL,
                voter_name TEXT,
                option_indexes TEXT NOT NULL,
                vote_count INTEGER NOT NULL DEFAULT 1,
                UNIQUE(conv_id, poll_timestamp, voter)
            );
            UPDATE schema_version SET version = 11;
            COMMIT;
        ",
    },
    Migration {
        version: 12,
        sql: "
            BEGIN;
            ALTER TABLE messages ADD COLUMN link_preview TEXT;
            UPDATE schema_version SET version = 12;
            COMMIT;
        ",
    },
    Migration {
        version: 13,
        sql: "
            BEGIN;
            ALTER TABLE messages ADD COLUMN body_raw TEXT;
            ALTER TABLE messages ADD COLUMN mentions_json TEXT;
            UPDATE schema_version SET version = 13;
            COMMIT;
        ",
    },
    Migration {
        version: 14,
        sql: "
            BEGIN;
            ALTER TABLE conversations ADD COLUMN mute_expires_at TEXT;
            UPDATE schema_version SET version = 14;
            COMMIT;
        ",
    },
];

pub struct Database {
    conn: Connection,
}

impl Database {
    pub fn open(path: &Path) -> Result<Self> {
        let conn = Connection::open(path)?;
        conn.execute_batch("PRAGMA journal_mode=WAL;")?;
        conn.execute_batch("PRAGMA foreign_keys=ON;")?;
        conn.execute_batch("PRAGMA secure_delete=ON;")?;
        let db = Self { conn };
        db.migrate()?;
        Ok(db)
    }

    pub fn open_in_memory() -> Result<Self> {
        let conn = Connection::open_in_memory()?;
        conn.execute_batch("PRAGMA foreign_keys=ON;")?;
        let db = Self { conn };
        db.migrate()?;
        Ok(db)
    }

    fn migrate(&self) -> Result<()> {
        self.conn.execute_batch(
            "CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL);",
        )?;

        let current: i32 = self.conn.query_row(
            "SELECT COALESCE(MAX(version), 0) FROM schema_version",
            [],
            |row| row.get(0),
        )?;

        for migration in MIGRATIONS {
            if current < migration.version {
                self.conn.execute_batch(migration.sql)?;
            }
        }
        Ok(())
    }

    // --- Conversations ---

    pub fn upsert_conversation(&self, id: &str, name: &str, is_group: bool) -> Result<()> {
        self.conn.execute(
            "INSERT INTO conversations (id, name, is_group)
             VALUES (?1, ?2, ?3)
             ON CONFLICT(id) DO UPDATE SET name = excluded.name",
            params![id, name, is_group as i32],
        )?;
        Ok(())
    }

    pub fn update_accepted(&self, id: &str, accepted: bool) -> Result<()> {
        self.conn.execute(
            "UPDATE conversations SET accepted = ?2 WHERE id = ?1",
            params![id, accepted as i32],
        )?;
        Ok(())
    }

    pub fn delete_conversation(&self, id: &str) -> Result<()> {
        self.conn.execute(
            "DELETE FROM reactions WHERE conversation_id = ?1",
            params![id],
        )?;
        self.conn.execute(
            "DELETE FROM messages WHERE conversation_id = ?1",
            params![id],
        )?;
        self.conn.execute(
            "DELETE FROM read_markers WHERE conversation_id = ?1",
            params![id],
        )?;
        self.conn
            .execute("DELETE FROM conversations WHERE id = ?1", params![id])?;
        Ok(())
    }

    /// Load a page of messages for a conversation, ordered chronologically (oldest first).
    /// `offset` skips the N most recent messages (for pagination).
    pub fn load_messages_page(
        &self,
        conv_id: &str,
        limit: usize,
        offset: usize,
    ) -> Result<Vec<DisplayMessage>> {
        let mut msg_stmt = self.conn.prepare(
            "SELECT sender, timestamp, body, is_system, status, timestamp_ms, is_edited, is_deleted, quote_author, quote_body, quote_ts_ms, sender_id, expires_in_seconds, expiration_start_ms, pinned, poll_data, link_preview, body_raw, mentions_json FROM messages
             WHERE conversation_id = ?1
             ORDER BY timestamp_ms DESC, rowid DESC LIMIT ?2 OFFSET ?3",
        )?;

        let mut messages: Vec<DisplayMessage> = msg_stmt
            .query_map(params![conv_id, limit as i64, offset as i64], |row| {
                let sender: String = row.get(0)?;
                let ts_str: String = row.get(1)?;
                let body: String = row.get(2)?;
                let is_system: bool = row.get::<_, i32>(3)? != 0;
                let status_i32: i32 = row.get(4)?;
                let timestamp_ms: i64 = row.get(5)?;
                let is_edited: bool = row.get::<_, i32>(6)? != 0;
                let is_deleted: bool = row.get::<_, i32>(7)? != 0;
                let quote_author: Option<String> = row.get(8)?;
                let quote_body: Option<String> = row.get(9)?;
                let quote_ts_ms: Option<i64> = row.get(10)?;
                let sender_id: String = row.get(11)?;
                let expires_in_seconds: i64 = row.get(12)?;
                let expiration_start_ms: i64 = row.get(13)?;
                let is_pinned: bool = row.get::<_, i32>(14)? != 0;
                let poll_data_json: Option<String> = row.get(15)?;
                let link_preview_json: Option<String> = row.get(16)?;
                let body_raw: Option<String> = row.get(17)?;
                let mentions_json: Option<String> = row.get(18)?;
                Ok((
                    sender,
                    ts_str,
                    body,
                    is_system,
                    status_i32,
                    timestamp_ms,
                    is_edited,
                    is_deleted,
                    quote_author,
                    quote_body,
                    quote_ts_ms,
                    sender_id,
                    expires_in_seconds,
                    expiration_start_ms,
                    is_pinned,
                    poll_data_json,
                    link_preview_json,
                    body_raw,
                    mentions_json,
                ))
            })?
            .filter_map(|r| r.ok())
            .filter_map(
                |(
                    sender,
                    ts_str,
                    body,
                    is_system,
                    status_i32,
                    timestamp_ms,
                    is_edited,
                    is_deleted,
                    quote_author,
                    quote_body,
                    quote_ts_ms,
                    sender_id,
                    expires_in_seconds,
                    expiration_start_ms,
                    is_pinned,
                    poll_data_json,
                    link_preview_json,
                    body_raw,
                    mentions_json,
                )| {
                    let timestamp = chrono::DateTime::parse_from_rfc3339(&ts_str)
                        .ok()?
                        .with_timezone(&chrono::Utc);
                    let quote = match (quote_author, quote_body, quote_ts_ms) {
                        (Some(author), Some(body), Some(ts)) => Some(crate::app::Quote {
                            author_id: author.clone(),
                            author,
                            body: body.replace('\u{FFFC}', ""),
                            timestamp_ms: ts,
                        }),
                        _ => None,
                    };
                    let poll_data =
                        poll_data_json.and_then(|j| serde_json::from_str::<PollData>(&j).ok());
                    let preview = link_preview_json
                        .and_then(|j| serde_json::from_str::<LinkPreview>(&j).ok());
                    let mentions: Vec<Mention> = mentions_json
                        .as_deref()
                        .and_then(|j| serde_json::from_str(j).ok())
                        .unwrap_or_default();
                    Some(DisplayMessage {
                        sender,
                        timestamp,
                        body,
                        is_system,
                        image_lines: None,
                        image_path: None,
                        status: MessageStatus::from_i32(status_i32),
                        timestamp_ms,
                        reactions: Vec::new(),
                        mention_ranges: Vec::new(),
                        style_ranges: Vec::new(),
                        body_raw,
                        mentions,
                        quote,
                        is_edited,
                        is_deleted,
                        is_pinned,
                        sender_id,
                        expires_in_seconds,
                        expiration_start_ms,
                        poll_data,
                        poll_votes: Vec::new(),
                        preview,
                        preview_image_lines: None,
                        preview_image_path: None,
                    })
                },
            )
            .collect();

        // Reverse so oldest first
        messages.reverse();

        // Attach reactions
        let mut ts_to_idx: HashMap<i64, Vec<usize>> = HashMap::new();
        for (i, m) in messages.iter().enumerate() {
            ts_to_idx.entry(m.timestamp_ms).or_default().push(i);
        }
        if let Ok(reactions) = self.load_reactions(conv_id) {
            for (target_ts, target_author, emoji, sender) in reactions {
                let idx = ts_to_idx.get(&target_ts).and_then(|idxs| {
                    idxs.iter()
                        .find(|&&i| {
                            messages[i].sender == target_author || messages[i].is_outgoing()
                        })
                        .or_else(|| idxs.first())
                        .copied()
                });
                if let Some(msg) = idx.and_then(|i| messages.get_mut(i)) {
                    if let Some(existing) = msg.reactions.iter_mut().find(|r| r.sender == sender) {
                        existing.emoji = emoji;
                    } else {
                        msg.reactions.push(Reaction { emoji, sender });
                    }
                }
            }
        }

        // Attach poll votes
        for msg in &mut messages {
            if msg.poll_data.is_some()
                && let Ok(votes) = self.load_poll_votes(conv_id, msg.timestamp_ms)
            {
                msg.poll_votes = votes;
            }
        }

        Ok(messages)
    }

    /// Load all conversations with their most recent messages (up to `msg_limit`).
    pub fn load_conversations(&self, msg_limit: usize) -> Result<Vec<Conversation>> {
        let mut stmt = self
            .conn
            .prepare("SELECT id, name, is_group, expiration_timer, accepted FROM conversations")?;

        let convs: Vec<(String, String, bool, i64, bool)> = stmt
            .query_map([], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, i32>(2)? != 0,
                    row.get::<_, i64>(3)?,
                    row.get::<_, i32>(4)? != 0,
                ))
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        let mut result = Vec::with_capacity(convs.len());

        for (id, name, is_group, expiration_timer, accepted) in convs {
            let messages = self.load_messages_page(&id, msg_limit, 0)?;
            let unread = self.unread_count(&id).unwrap_or(0);

            result.push(Conversation {
                name,
                id: id.clone(),
                messages,
                unread,
                is_group,
                expiration_timer,
                accepted,
            });
        }

        Ok(result)
    }

    /// Load conversation IDs ordered by most recent message.
    pub fn load_conversation_order(&self) -> Result<Vec<String>> {
        let mut stmt = self.conn.prepare(
            "SELECT c.id FROM conversations c
             LEFT JOIN messages m ON m.conversation_id = c.id
             GROUP BY c.id
             ORDER BY COALESCE(MAX(m.rowid), 0) DESC",
        )?;

        let ids: Vec<String> = stmt
            .query_map([], |row| row.get(0))?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(ids)
    }

    // --- Messages ---

    #[allow(clippy::too_many_arguments, dead_code)]
    pub fn insert_message(
        &self,
        conv_id: &str,
        sender: &str,
        timestamp: &str,
        body: &str,
        is_system: bool,
        status: Option<MessageStatus>,
        timestamp_ms: i64,
    ) -> Result<i64> {
        self.insert_message_full(
            conv_id,
            sender,
            timestamp,
            body,
            is_system,
            status,
            timestamp_ms,
            "",
            None,
            None,
            None,
            0,
            0,
        )
    }

    #[allow(clippy::too_many_arguments)]
    pub fn insert_message_full(
        &self,
        conv_id: &str,
        sender: &str,
        timestamp: &str,
        body: &str,
        is_system: bool,
        status: Option<MessageStatus>,
        timestamp_ms: i64,
        sender_id: &str,
        quote_author: Option<&str>,
        quote_body: Option<&str>,
        quote_ts_ms: Option<i64>,
        expires_in_seconds: i64,
        expiration_start_ms: i64,
    ) -> Result<i64> {
        let status_i32 = status.map(|s| s.to_i32()).unwrap_or(0);
        self.conn.execute(
            "INSERT INTO messages (conversation_id, sender, timestamp, body, is_system, status, timestamp_ms, sender_id, quote_author, quote_body, quote_ts_ms, expires_in_seconds, expiration_start_ms)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)",
            params![conv_id, sender, timestamp, body, is_system as i32, status_i32, timestamp_ms, sender_id, quote_author, quote_body, quote_ts_ms, expires_in_seconds, expiration_start_ms],
        )?;
        Ok(self.conn.last_insert_rowid())
    }

    /// Update delivery status for an outgoing message by its ms epoch timestamp.
    pub fn update_message_status(
        &self,
        conv_id: &str,
        timestamp_ms: i64,
        status: i32,
    ) -> Result<()> {
        self.conn.execute(
            "UPDATE messages SET status = ?3
             WHERE conversation_id = ?1 AND timestamp_ms = ?2 AND sender = 'you' AND status < ?3",
            params![conv_id, timestamp_ms, status],
        )?;
        Ok(())
    }

    /// Update timestamp_ms and status for an outgoing message when the server assigns
    /// a canonical timestamp (replacing the local one).
    pub fn update_message_timestamp_ms(
        &self,
        conv_id: &str,
        old_ts: i64,
        new_ts: i64,
        status: i32,
    ) -> Result<()> {
        self.conn.execute(
            "UPDATE messages SET timestamp_ms = ?3, status = ?4
             WHERE conversation_id = ?1 AND timestamp_ms = ?2 AND sender = 'you'",
            params![conv_id, old_ts, new_ts, status],
        )?;
        Ok(())
    }

    // --- Read markers ---

    pub fn save_read_marker(&self, conv_id: &str, last_rowid: i64) -> Result<()> {
        self.conn.execute(
            "INSERT INTO read_markers (conversation_id, last_read_rowid)
             VALUES (?1, ?2)
             ON CONFLICT(conversation_id) DO UPDATE SET last_read_rowid = excluded.last_read_rowid",
            params![conv_id, last_rowid],
        )?;
        Ok(())
    }

    pub fn last_message_rowid(&self, conv_id: &str) -> Result<Option<i64>> {
        let result = self.conn.query_row(
            "SELECT MAX(rowid) FROM messages WHERE conversation_id = ?1",
            params![conv_id],
            |row| row.get::<_, Option<i64>>(0),
        )?;
        Ok(result)
    }

    pub fn unread_count(&self, conv_id: &str) -> Result<usize> {
        let last_read: i64 = self.conn.query_row(
            "SELECT COALESCE(
                    (SELECT last_read_rowid FROM read_markers WHERE conversation_id = ?1),
                    0
                 )",
            params![conv_id],
            |row| row.get(0),
        )?;

        let count: i64 = self.conn.query_row(
            "SELECT COUNT(*) FROM messages
             WHERE conversation_id = ?1 AND rowid > ?2 AND is_system = 0",
            params![conv_id, last_read],
            |row| row.get(0),
        )?;

        Ok(count as usize)
    }

    // --- Reactions ---

    pub fn upsert_reaction(
        &self,
        conv_id: &str,
        target_ts_ms: i64,
        target_author: &str,
        sender: &str,
        emoji: &str,
    ) -> Result<()> {
        self.conn.execute(
            "INSERT INTO reactions (conversation_id, target_ts_ms, target_author, sender, emoji)
             VALUES (?1, ?2, ?3, ?4, ?5)
             ON CONFLICT(conversation_id, target_ts_ms, target_author, sender)
             DO UPDATE SET emoji = excluded.emoji",
            params![conv_id, target_ts_ms, target_author, sender, emoji],
        )?;
        Ok(())
    }

    pub fn remove_reaction(
        &self,
        conv_id: &str,
        target_ts_ms: i64,
        target_author: &str,
        sender: &str,
    ) -> Result<()> {
        self.conn.execute(
            "DELETE FROM reactions
             WHERE conversation_id = ?1 AND target_ts_ms = ?2
               AND target_author = ?3 AND sender = ?4",
            params![conv_id, target_ts_ms, target_author, sender],
        )?;
        Ok(())
    }

    /// Load all reactions for a conversation.
    /// Returns (target_ts_ms, target_author, emoji, sender) tuples.
    pub fn load_reactions(&self, conv_id: &str) -> Result<Vec<(i64, String, String, String)>> {
        let mut stmt = self.conn.prepare(
            "SELECT target_ts_ms, target_author, emoji, sender FROM reactions
             WHERE conversation_id = ?1",
        )?;
        let rows: Vec<(i64, String, String, String)> = stmt
            .query_map(params![conv_id], |row| {
                Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;
        Ok(rows)
    }

    /// Update the body and mark a message as edited.
    pub fn update_message_body(&self, conv_id: &str, timestamp_ms: i64, body: &str) -> Result<()> {
        self.conn.execute(
            "UPDATE messages SET body = ?3, is_edited = 1
             WHERE conversation_id = ?1 AND timestamp_ms = ?2",
            params![conv_id, timestamp_ms, body],
        )?;
        Ok(())
    }

    /// Mark a message as locally deleted.
    pub fn mark_message_deleted(&self, conv_id: &str, timestamp_ms: i64) -> Result<()> {
        self.conn.execute(
            "UPDATE messages SET is_deleted = 1, body = '[deleted]'
             WHERE conversation_id = ?1 AND timestamp_ms = ?2",
            params![conv_id, timestamp_ms],
        )?;
        Ok(())
    }

    /// Set the pinned state of a message.
    pub fn set_message_pinned(&self, conv_id: &str, timestamp_ms: i64, pinned: bool) -> Result<()> {
        self.conn.execute(
            "UPDATE messages SET pinned = ?3
             WHERE conversation_id = ?1 AND timestamp_ms = ?2",
            params![conv_id, timestamp_ms, pinned as i32],
        )?;
        Ok(())
    }

    // --- Search ---

    /// Search messages in a specific conversation using case-insensitive LIKE.
    /// Returns (sender, body, timestamp_ms, conversation_id, conversation_name) tuples,
    /// most recent first, limited to `limit` results.
    pub fn search_messages(
        &self,
        conv_id: &str,
        query: &str,
        limit: usize,
    ) -> Result<Vec<SearchRow>> {
        let escaped = query
            .replace('\\', "\\\\")
            .replace('%', "\\%")
            .replace('_', "\\_");
        let pattern = format!("%{escaped}%");
        let mut stmt = self.conn.prepare(
            "SELECT m.sender, m.body, m.timestamp_ms, c.id, c.name
             FROM messages m
             JOIN conversations c ON c.id = m.conversation_id
             WHERE m.conversation_id = ?1
               AND m.body LIKE ?2 ESCAPE '\\' COLLATE NOCASE
               AND m.is_system = 0
               AND m.is_deleted = 0
             ORDER BY m.timestamp_ms DESC
             LIMIT ?3",
        )?;
        let rows = stmt
            .query_map(params![conv_id, pattern, limit as i64], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, i64>(2)?,
                    row.get::<_, String>(3)?,
                    row.get::<_, String>(4)?,
                ))
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;
        Ok(rows)
    }

    /// Search messages across all conversations using case-insensitive LIKE.
    /// Returns (sender, body, timestamp_ms, conversation_id, conversation_name) tuples,
    /// most recent first, limited to `limit` results.
    pub fn search_all_messages(&self, query: &str, limit: usize) -> Result<Vec<SearchRow>> {
        let escaped = query
            .replace('\\', "\\\\")
            .replace('%', "\\%")
            .replace('_', "\\_");
        let pattern = format!("%{escaped}%");
        let mut stmt = self.conn.prepare(
            "SELECT m.sender, m.body, m.timestamp_ms, c.id, c.name
             FROM messages m
             JOIN conversations c ON c.id = m.conversation_id
             WHERE m.body LIKE ?1 ESCAPE '\\' COLLATE NOCASE
               AND m.is_system = 0
               AND m.is_deleted = 0
             ORDER BY m.timestamp_ms DESC
             LIMIT ?2",
        )?;
        let rows = stmt
            .query_map(params![pattern, limit as i64], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, i64>(2)?,
                    row.get::<_, String>(3)?,
                    row.get::<_, String>(4)?,
                ))
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;
        Ok(rows)
    }

    /// Find the max rowid for messages up to (and including) a given timestamp.
    /// Uses the idx_messages_conv_ts_ms index for efficient lookup.
    pub fn max_rowid_up_to_timestamp(
        &self,
        conv_id: &str,
        timestamp_ms: i64,
    ) -> Result<Option<i64>> {
        let result = self.conn.query_row(
            "SELECT MAX(rowid) FROM messages WHERE conversation_id = ?1 AND timestamp_ms <= ?2",
            params![conv_id, timestamp_ms],
            |row| row.get::<_, Option<i64>>(0),
        )?;
        Ok(result)
    }

    // --- Muted conversations ---

    /// Persist a mute state. `None` unmutes the conversation.
    pub fn set_mute(&self, conv_id: &str, state: Option<MuteState>) -> Result<()> {
        let (muted, expires_str) = match state {
            None => (0, None),
            Some(MuteState::Permanent) => (1, None),
            Some(MuteState::Until(t)) => (1, Some(t.to_rfc3339())),
        };
        self.conn.execute(
            "UPDATE conversations SET muted = ?2, mute_expires_at = ?3 WHERE id = ?1",
            params![conv_id, muted, expires_str],
        )?;
        Ok(())
    }

    pub fn load_mutes(&self) -> Result<HashMap<String, MuteState>> {
        let mut stmt = self
            .conn
            .prepare("SELECT id, mute_expires_at FROM conversations WHERE muted = 1")?;
        let rows = stmt
            .query_map([], |row| {
                let id: String = row.get(0)?;
                let expires: Option<String> = row.get(1)?;
                Ok((id, expires))
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;
        let mut map = HashMap::new();
        for (id, expires_str) in rows {
            let state = match expires_str.and_then(|s| DateTime::parse_from_rfc3339(&s).ok()) {
                Some(dt) => MuteState::Until(dt.with_timezone(&Utc)),
                None => MuteState::Permanent,
            };
            map.insert(id, state);
        }
        Ok(map)
    }

    /// Clear mutes whose expiry has passed. Returns the conversation IDs that were unmuted.
    pub fn clear_expired_mutes(&self, now: DateTime<Utc>) -> Result<Vec<String>> {
        let now_str = now.to_rfc3339();
        let mut stmt = self.conn.prepare(
            "UPDATE conversations SET muted = 0, mute_expires_at = NULL
             WHERE muted = 1 AND mute_expires_at IS NOT NULL AND mute_expires_at <= ?1
             RETURNING id",
        )?;
        let ids = stmt
            .query_map(params![now_str], |row| row.get(0))?
            .collect::<std::result::Result<Vec<String>, _>>()?;
        Ok(ids)
    }

    // --- Blocked conversations ---

    pub fn set_blocked(&self, conv_id: &str, blocked: bool) -> Result<()> {
        self.conn.execute(
            "UPDATE conversations SET blocked = ?2 WHERE id = ?1",
            params![conv_id, blocked as i32],
        )?;
        Ok(())
    }

    pub fn load_blocked(&self) -> Result<std::collections::HashSet<String>> {
        let mut stmt = self
            .conn
            .prepare("SELECT id FROM conversations WHERE blocked = 1")?;
        let ids: Vec<String> = stmt
            .query_map([], |row| row.get(0))?
            .collect::<std::result::Result<Vec<_>, _>>()?;
        Ok(ids.into_iter().collect())
    }

    // --- Disappearing messages ---

    pub fn update_expiration_timer(&self, conv_id: &str, seconds: i64) -> Result<()> {
        self.conn.execute(
            "UPDATE conversations SET expiration_timer = ?2 WHERE id = ?1",
            params![conv_id, seconds],
        )?;
        Ok(())
    }

    pub fn delete_expired_messages(&self, now_ms: i64) -> Result<usize> {
        let deleted = self.conn.execute(
            "DELETE FROM messages WHERE expires_in_seconds > 0
             AND expiration_start_ms > 0
             AND (expiration_start_ms + expires_in_seconds * 1000) < ?1",
            params![now_ms],
        )?;
        Ok(deleted)
    }

    // --- Polls ---

    pub fn upsert_poll_data(
        &self,
        conv_id: &str,
        timestamp_ms: i64,
        poll_data: &PollData,
    ) -> Result<()> {
        let json = serde_json::to_string(poll_data)?;
        self.conn.execute(
            "UPDATE messages SET poll_data = ?3
             WHERE conversation_id = ?1 AND timestamp_ms = ?2",
            params![conv_id, timestamp_ms, json],
        )?;
        Ok(())
    }

    pub fn upsert_link_preview(
        &self,
        conv_id: &str,
        timestamp_ms: i64,
        preview: &LinkPreview,
    ) -> Result<()> {
        let json = serde_json::to_string(preview)?;
        self.conn.execute(
            "UPDATE messages SET link_preview = ?3
             WHERE conversation_id = ?1 AND timestamp_ms = ?2",
            params![conv_id, timestamp_ms, json],
        )?;
        Ok(())
    }

    /// Store the raw body (with U+FFFC placeholders) and raw mentions for a message,
    /// so later contact list updates can re-resolve the display body.
    pub fn upsert_message_mentions(
        &self,
        conv_id: &str,
        timestamp_ms: i64,
        body_raw: &str,
        mentions: &[Mention],
    ) -> Result<()> {
        let json = serde_json::to_string(mentions)?;
        self.conn.execute(
            "UPDATE messages SET body_raw = ?3, mentions_json = ?4
             WHERE conversation_id = ?1 AND timestamp_ms = ?2",
            params![conv_id, timestamp_ms, body_raw, json],
        )?;
        Ok(())
    }

    pub fn upsert_poll_vote(
        &self,
        conv_id: &str,
        poll_timestamp: i64,
        voter: &str,
        voter_name: Option<&str>,
        option_indexes: &[i64],
        vote_count: i64,
    ) -> Result<()> {
        let indexes_json = serde_json::to_string(option_indexes)?;
        self.conn.execute(
            "INSERT INTO poll_votes (conv_id, poll_timestamp, voter, voter_name, option_indexes, vote_count)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6)
             ON CONFLICT(conv_id, poll_timestamp, voter)
             DO UPDATE SET option_indexes = excluded.option_indexes, vote_count = excluded.vote_count, voter_name = excluded.voter_name",
            params![conv_id, poll_timestamp, voter, voter_name, indexes_json, vote_count],
        )?;
        Ok(())
    }

    pub fn load_poll_votes(&self, conv_id: &str, poll_timestamp: i64) -> Result<Vec<PollVote>> {
        let mut stmt = self.conn.prepare(
            "SELECT voter, voter_name, option_indexes, vote_count FROM poll_votes
             WHERE conv_id = ?1 AND poll_timestamp = ?2",
        )?;
        let rows: Vec<PollVote> = stmt
            .query_map(params![conv_id, poll_timestamp], |row| {
                let voter: String = row.get(0)?;
                let voter_name: Option<String> = row.get(1)?;
                let indexes_json: String = row.get(2)?;
                let vote_count: i64 = row.get(3)?;
                let option_indexes: Vec<i64> =
                    serde_json::from_str(&indexes_json).unwrap_or_default();
                Ok(PollVote {
                    voter,
                    voter_name,
                    option_indexes,
                    vote_count,
                })
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;
        Ok(rows)
    }

    pub fn close_poll(&self, conv_id: &str, poll_timestamp: i64) -> Result<()> {
        let poll_json: Option<String> = self
            .conn
            .query_row(
                "SELECT poll_data FROM messages WHERE conversation_id = ?1 AND timestamp_ms = ?2",
                params![conv_id, poll_timestamp],
                |row| row.get(0),
            )
            .ok()
            .flatten();
        if let Some(json_str) = poll_json
            && let Ok(mut poll_data) = serde_json::from_str::<PollData>(&json_str)
        {
            poll_data.closed = true;
            let updated = serde_json::to_string(&poll_data)?;
            self.conn.execute(
                "UPDATE messages SET poll_data = ?3
                     WHERE conversation_id = ?1 AND timestamp_ms = ?2",
                params![conv_id, poll_timestamp, updated],
            )?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rstest::{fixture, rstest};

    #[fixture]
    fn db() -> Database {
        Database::open_in_memory().unwrap()
    }

    #[rstest]
    fn migration_creates_tables(db: Database) {
        // Should be able to query conversations table
        let count: i64 = db
            .conn
            .query_row("SELECT COUNT(*) FROM conversations", [], |row| row.get(0))
            .unwrap();
        assert_eq!(count, 0);
    }

    /// Regression guard: after migrate(), schema_version must match the last
    /// migration in the table. Catches the obvious "added a migration but
    /// forgot to append it" or "renumbered a version" mistakes.
    #[rstest]
    fn migrations_advance_schema_version_monotonically(db: Database) {
        let max_in_table: i32 = db
            .conn
            .query_row("SELECT MAX(version) FROM schema_version", [], |row| {
                row.get(0)
            })
            .unwrap();
        let expected = MIGRATIONS
            .last()
            .expect("MIGRATIONS must not be empty")
            .version;
        assert_eq!(max_in_table, expected);

        // Versions in the table must be strictly increasing and contiguous.
        let mut prev = 0;
        for migration in MIGRATIONS {
            assert_eq!(
                migration.version,
                prev + 1,
                "migration versions must be contiguous (got {} after {})",
                migration.version,
                prev
            );
            prev = migration.version;
        }
    }

    #[rstest]
    fn upsert_and_load_conversations(db: Database) {
        db.upsert_conversation("+1", "Alice", false).unwrap();
        db.upsert_conversation("g1", "Family", true).unwrap();

        let convs = db.load_conversations(100).unwrap();
        assert_eq!(convs.len(), 2);
    }

    #[rstest]
    fn name_update_on_conflict(db: Database) {
        db.upsert_conversation("+1", "Unknown", false).unwrap();
        db.upsert_conversation("+1", "Alice", false).unwrap();

        let convs = db.load_conversations(100).unwrap();
        assert_eq!(convs.len(), 1);
        assert_eq!(convs[0].name, "Alice");
    }

    #[rstest]
    fn insert_and_load_messages(db: Database) {
        db.upsert_conversation("+1", "Alice", false).unwrap();
        db.insert_message(
            "+1",
            "Alice",
            "2025-01-01T00:00:00Z",
            "hello",
            false,
            None,
            0,
        )
        .unwrap();
        db.insert_message("+1", "you", "2025-01-01T00:01:00Z", "hi!", false, None, 0)
            .unwrap();

        let convs = db.load_conversations(100).unwrap();
        assert_eq!(convs[0].messages.len(), 2);
        assert_eq!(convs[0].messages[0].body, "hello");
        assert_eq!(convs[0].messages[1].body, "hi!");
    }

    #[rstest]
    fn unread_count_with_read_markers(db: Database) {
        db.upsert_conversation("+1", "Alice", false).unwrap();
        let r1 = db
            .insert_message(
                "+1",
                "Alice",
                "2025-01-01T00:00:00Z",
                "msg1",
                false,
                None,
                0,
            )
            .unwrap();
        db.insert_message(
            "+1",
            "Alice",
            "2025-01-01T00:01:00Z",
            "msg2",
            false,
            None,
            0,
        )
        .unwrap();
        db.insert_message(
            "+1",
            "Alice",
            "2025-01-01T00:02:00Z",
            "msg3",
            false,
            None,
            0,
        )
        .unwrap();

        // Mark first message as read
        db.save_read_marker("+1", r1).unwrap();
        assert_eq!(db.unread_count("+1").unwrap(), 2);
    }

    #[rstest]
    fn system_messages_excluded_from_unread(db: Database) {
        db.upsert_conversation("+1", "Alice", false).unwrap();
        db.insert_message(
            "+1",
            "",
            "2025-01-01T00:00:00Z",
            "system msg",
            true,
            None,
            0,
        )
        .unwrap();
        db.insert_message(
            "+1",
            "Alice",
            "2025-01-01T00:01:00Z",
            "real msg",
            false,
            None,
            0,
        )
        .unwrap();

        // No read marker → only non-system messages count as unread
        assert_eq!(db.unread_count("+1").unwrap(), 1);
    }

    #[rstest]
    fn conversation_order(db: Database) {
        db.upsert_conversation("+1", "Alice", false).unwrap();
        db.upsert_conversation("+2", "Bob", false).unwrap();
        // Alice gets an older message, Bob gets a newer one
        db.insert_message("+1", "Alice", "2025-01-01T00:00:00Z", "old", false, None, 0)
            .unwrap();
        db.insert_message("+2", "Bob", "2025-01-02T00:00:00Z", "new", false, None, 0)
            .unwrap();

        let order = db.load_conversation_order().unwrap();
        // Most recent message first
        assert_eq!(order[0], "+2");
        assert_eq!(order[1], "+1");
    }

    // --- Boolean flag round-trip: blocked ---

    #[rstest]
    fn blocked_flag_round_trip(db: Database) {
        db.upsert_conversation("+1", "Alice", false).unwrap();
        db.upsert_conversation("+2", "Bob", false).unwrap();

        db.set_blocked("+1", true).unwrap();
        let set = db.load_blocked().unwrap();
        assert!(set.contains("+1"));
        assert!(!set.contains("+2"));

        db.set_blocked("+1", false).unwrap();
        let set = db.load_blocked().unwrap();
        assert!(!set.contains("+1"));
    }

    // --- Muted flag round-trips ---

    #[rstest]
    fn permanent_mute_round_trip(db: Database) {
        db.upsert_conversation("+1", "Alice", false).unwrap();
        db.upsert_conversation("+2", "Bob", false).unwrap();

        db.set_mute("+1", Some(MuteState::Permanent)).unwrap();
        let map = db.load_mutes().unwrap();
        assert_eq!(map.get("+1"), Some(&MuteState::Permanent));
        assert!(!map.contains_key("+2"));

        db.set_mute("+1", None).unwrap();
        let map = db.load_mutes().unwrap();
        assert!(!map.contains_key("+1"));
    }

    #[rstest]
    fn timed_mute_round_trip(db: Database) {
        use chrono::TimeZone;
        db.upsert_conversation("+1", "Alice", false).unwrap();

        let expiry = Utc.with_ymd_and_hms(2026, 6, 15, 12, 0, 0).unwrap();
        db.set_mute("+1", Some(MuteState::Until(expiry))).unwrap();
        let map = db.load_mutes().unwrap();
        assert_eq!(map["+1"], MuteState::Until(expiry));
    }

    #[rstest]
    fn clear_expired_mutes_clears_past(db: Database) {
        use chrono::TimeZone;
        db.upsert_conversation("+1", "Alice", false).unwrap();
        db.upsert_conversation("+2", "Bob", false).unwrap();

        let past = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let future = Utc.with_ymd_and_hms(2099, 1, 1, 0, 0, 0).unwrap();
        let now = Utc.with_ymd_and_hms(2026, 6, 1, 0, 0, 0).unwrap();

        // +1 has expired timed mute, +2 has future timed mute
        db.set_mute("+1", Some(MuteState::Until(past))).unwrap();
        db.set_mute("+2", Some(MuteState::Until(future))).unwrap();

        let cleared = db.clear_expired_mutes(now).unwrap();
        assert_eq!(cleared, vec!["+1"]);

        let map = db.load_mutes().unwrap();
        assert!(!map.contains_key("+1")); // cleared
        assert!(map.contains_key("+2")); // still muted
    }

    #[rstest]
    fn clear_expired_mutes_skips_permanent(db: Database) {
        use chrono::TimeZone;
        db.upsert_conversation("+1", "Alice", false).unwrap();

        db.set_mute("+1", Some(MuteState::Permanent)).unwrap();

        let now = Utc.with_ymd_and_hms(2099, 1, 1, 0, 0, 0).unwrap();
        let cleared = db.clear_expired_mutes(now).unwrap();
        assert!(cleared.is_empty());

        let map = db.load_mutes().unwrap();
        assert!(map.contains_key("+1")); // still muted
    }

    #[rstest]
    fn last_message_rowid(db: Database) {
        db.upsert_conversation("+1", "Alice", false).unwrap();

        assert_eq!(db.last_message_rowid("+1").unwrap(), None);

        db.insert_message(
            "+1",
            "Alice",
            "2025-01-01T00:00:00Z",
            "msg1",
            false,
            None,
            0,
        )
        .unwrap();
        let r2 = db
            .insert_message(
                "+1",
                "Alice",
                "2025-01-01T00:01:00Z",
                "msg2",
                false,
                None,
                0,
            )
            .unwrap();

        assert_eq!(db.last_message_rowid("+1").unwrap(), Some(r2));
    }

    #[rstest]
    fn max_rowid_up_to_timestamp(db: Database) {
        db.upsert_conversation("+1", "Alice", false).unwrap();

        // No messages → None
        assert_eq!(db.max_rowid_up_to_timestamp("+1", 5000).unwrap(), None);

        let r1 = db
            .insert_message(
                "+1",
                "Alice",
                "2025-01-01T00:00:00Z",
                "msg1",
                false,
                None,
                1000,
            )
            .unwrap();
        let r2 = db
            .insert_message(
                "+1",
                "Alice",
                "2025-01-01T00:01:00Z",
                "msg2",
                false,
                None,
                2000,
            )
            .unwrap();
        let _r3 = db
            .insert_message(
                "+1",
                "Alice",
                "2025-01-01T00:02:00Z",
                "msg3",
                false,
                None,
                3000,
            )
            .unwrap();

        // Timestamp before all messages → None
        assert_eq!(db.max_rowid_up_to_timestamp("+1", 500).unwrap(), None);

        // Timestamp matching first message
        assert_eq!(db.max_rowid_up_to_timestamp("+1", 1000).unwrap(), Some(r1));

        // Timestamp matching second message
        assert_eq!(db.max_rowid_up_to_timestamp("+1", 2000).unwrap(), Some(r2));

        // Timestamp between second and third
        assert_eq!(db.max_rowid_up_to_timestamp("+1", 2500).unwrap(), Some(r2));
    }

    #[rstest]
    fn load_messages_page_pagination(db: Database) {
        db.upsert_conversation("+1", "Alice", false).unwrap();
        for i in 0..5 {
            db.insert_message(
                "+1",
                "Alice",
                &format!("2025-01-01T00:0{i}:00Z"),
                &format!("msg{i}"),
                false,
                None,
                i * 1000,
            )
            .unwrap();
        }

        // Load first page (most recent 3)
        let page1 = db.load_messages_page("+1", 3, 0).unwrap();
        assert_eq!(page1.len(), 3);
        assert_eq!(page1[0].body, "msg2"); // oldest of the 3 most recent
        assert_eq!(page1[2].body, "msg4"); // newest

        // Load second page (next 2 older)
        let page2 = db.load_messages_page("+1", 3, 3).unwrap();
        assert_eq!(page2.len(), 2);
        assert_eq!(page2[0].body, "msg0"); // oldest overall
        assert_eq!(page2[1].body, "msg1");

        // Load third page (nothing left)
        let page3 = db.load_messages_page("+1", 3, 5).unwrap();
        assert!(page3.is_empty());
    }

    #[rstest]
    fn migration_v4_creates_reactions_table(db: Database) {
        // Should be able to query reactions table
        let count: i64 = db
            .conn
            .query_row("SELECT COUNT(*) FROM reactions", [], |row| row.get(0))
            .unwrap();
        assert_eq!(count, 0);
    }

    #[rstest]
    fn upsert_reaction_insert_and_replace(db: Database) {
        db.upsert_conversation("+1", "Alice", false).unwrap();
        db.insert_message(
            "+1",
            "Alice",
            "2025-01-01T00:00:00Z",
            "hello",
            false,
            None,
            1000,
        )
        .unwrap();

        // Insert a reaction
        db.upsert_reaction("+1", 1000, "Alice", "Bob", "👍")
            .unwrap();
        let reactions = db.load_reactions("+1").unwrap();
        assert_eq!(reactions.len(), 1);
        assert_eq!(
            reactions[0],
            (
                1000,
                "Alice".to_string(),
                "👍".to_string(),
                "Bob".to_string()
            )
        );

        // Replace: same sender reacts with different emoji
        db.upsert_reaction("+1", 1000, "Alice", "Bob", "❤️")
            .unwrap();
        let reactions = db.load_reactions("+1").unwrap();
        assert_eq!(reactions.len(), 1);
        assert_eq!(reactions[0].2, "❤️");
    }

    #[rstest]
    fn remove_reaction(db: Database) {
        db.upsert_conversation("+1", "Alice", false).unwrap();

        db.upsert_reaction("+1", 1000, "Alice", "Bob", "👍")
            .unwrap();
        assert_eq!(db.load_reactions("+1").unwrap().len(), 1);

        db.remove_reaction("+1", 1000, "Alice", "Bob").unwrap();
        assert_eq!(db.load_reactions("+1").unwrap().len(), 0);
    }

    #[rstest]
    fn load_reactions_attaches_to_messages(db: Database) {
        db.upsert_conversation("+1", "Alice", false).unwrap();
        db.insert_message(
            "+1",
            "Alice",
            "2025-01-01T00:00:00Z",
            "hello",
            false,
            None,
            1000,
        )
        .unwrap();
        db.insert_message("+1", "you", "2025-01-01T00:01:00Z", "hi", false, None, 2000)
            .unwrap();

        db.upsert_reaction("+1", 1000, "Alice", "Bob", "👍")
            .unwrap();
        db.upsert_reaction("+1", 2000, "you", "Alice", "❤️")
            .unwrap();

        let convs = db.load_conversations(100).unwrap();
        assert_eq!(convs[0].messages[0].reactions.len(), 1);
        assert_eq!(convs[0].messages[0].reactions[0].emoji, "👍");
        assert_eq!(convs[0].messages[1].reactions.len(), 1);
        assert_eq!(convs[0].messages[1].reactions[0].emoji, "❤️");
    }

    #[rstest]
    fn search_messages_in_conversation(db: Database) {
        db.upsert_conversation("+1", "Alice", false).unwrap();
        db.insert_message(
            "+1",
            "Alice",
            "2025-01-01T00:00:00Z",
            "hello world",
            false,
            None,
            1000,
        )
        .unwrap();
        db.insert_message(
            "+1",
            "you",
            "2025-01-01T00:01:00Z",
            "hi there",
            false,
            None,
            2000,
        )
        .unwrap();
        db.insert_message(
            "+1",
            "Alice",
            "2025-01-01T00:02:00Z",
            "Hello again",
            false,
            None,
            3000,
        )
        .unwrap();

        // Case-insensitive search for "hello"
        let results = db.search_messages("+1", "hello", 50).unwrap();
        assert_eq!(results.len(), 2);
        // Most recent first
        assert_eq!(results[0].1, "Hello again");
        assert_eq!(results[1].1, "hello world");
    }

    #[rstest]
    fn search_messages_excludes_system_and_deleted(db: Database) {
        db.upsert_conversation("+1", "Alice", false).unwrap();
        db.insert_message(
            "+1",
            "",
            "2025-01-01T00:00:00Z",
            "system hello",
            true,
            None,
            1000,
        )
        .unwrap();
        db.insert_message(
            "+1",
            "Alice",
            "2025-01-01T00:01:00Z",
            "real hello",
            false,
            None,
            2000,
        )
        .unwrap();

        let results = db.search_messages("+1", "hello", 50).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].1, "real hello");
    }

    #[rstest]
    fn migration_v8_defaults_accepted_to_1(db: Database) {
        db.upsert_conversation("+1", "Alice", false).unwrap();
        let convs = db.load_conversations(100).unwrap();
        assert!(convs[0].accepted);
    }

    #[rstest]
    fn update_accepted_round_trip(db: Database) {
        db.upsert_conversation("+1", "Alice", false).unwrap();
        db.update_accepted("+1", false).unwrap();
        let convs = db.load_conversations(100).unwrap();
        assert!(!convs[0].accepted);

        db.update_accepted("+1", true).unwrap();
        let convs = db.load_conversations(100).unwrap();
        assert!(convs[0].accepted);
    }

    #[rstest]
    fn delete_conversation_removes_all_data(db: Database) {
        db.upsert_conversation("+1", "Alice", false).unwrap();
        db.insert_message(
            "+1",
            "Alice",
            "2025-01-01T00:00:00Z",
            "hello",
            false,
            None,
            1000,
        )
        .unwrap();
        db.upsert_reaction("+1", 1000, "Alice", "Bob", "👍")
            .unwrap();
        db.save_read_marker("+1", 1).unwrap();

        db.delete_conversation("+1").unwrap();

        let convs = db.load_conversations(100).unwrap();
        assert!(convs.is_empty());
        assert_eq!(db.load_reactions("+1").unwrap().len(), 0);
    }

    #[rstest]
    fn migration_v9_defaults_blocked_to_0(db: Database) {
        db.upsert_conversation("+1", "Alice", false).unwrap();
        let blocked = db.load_blocked().unwrap();
        assert!(!blocked.contains("+1"));
    }

    #[rstest]
    fn search_all_messages_across_conversations(db: Database) {
        db.upsert_conversation("+1", "Alice", false).unwrap();
        db.upsert_conversation("+2", "Bob", false).unwrap();
        db.insert_message(
            "+1",
            "Alice",
            "2025-01-01T00:00:00Z",
            "hello from alice",
            false,
            None,
            1000,
        )
        .unwrap();
        db.insert_message(
            "+2",
            "Bob",
            "2025-01-01T00:01:00Z",
            "hello from bob",
            false,
            None,
            2000,
        )
        .unwrap();

        let results = db.search_all_messages("hello", 50).unwrap();
        assert_eq!(results.len(), 2);
        // Most recent first
        assert_eq!(results[0].3, "+2"); // Bob's conversation
        assert_eq!(results[1].3, "+1"); // Alice's conversation
    }
}