nzb-core 0.2.4

Shared models, config, NZB parser, and SQLite database for NZB clients
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
use std::path::Path;

use chrono::Utc;
use rusqlite::{Connection, params};
use tracing::info;

use crate::error::NzbError;
use crate::models::*;

#[allow(dead_code)]
const SCHEMA_VERSION: u32 = 1;

/// Database handle for queue and history persistence.
pub struct Database {
    pub(crate) conn: Connection,
}

impl Database {
    /// Open (or create) the database at the given path.
    pub fn open(path: &Path) -> Result<Self, NzbError> {
        let conn = Connection::open(path)?;

        // Enable WAL mode for concurrent reads during downloads
        conn.execute_batch("PRAGMA journal_mode=WAL;")?;
        conn.execute_batch("PRAGMA foreign_keys=ON;")?;

        let db = Self { conn };
        db.migrate()?;
        Ok(db)
    }

    /// Open an in-memory database (for testing).
    pub fn open_memory() -> Result<Self, NzbError> {
        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<(), NzbError> {
        self.conn.execute_batch(
            "CREATE TABLE IF NOT EXISTS schema_version (
                version INTEGER NOT NULL
            );",
        )?;

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

        if version < 1 {
            info!("Applying database migration v1");
            self.conn.execute_batch(
                "
                -- Active download queue
                CREATE TABLE IF NOT EXISTS queue (
                    id TEXT PRIMARY KEY,
                    name TEXT NOT NULL,
                    category TEXT NOT NULL DEFAULT 'Default',
                    status TEXT NOT NULL DEFAULT 'queued',
                    priority INTEGER NOT NULL DEFAULT 1,
                    total_bytes INTEGER NOT NULL DEFAULT 0,
                    downloaded_bytes INTEGER NOT NULL DEFAULT 0,
                    file_count INTEGER NOT NULL DEFAULT 0,
                    files_completed INTEGER NOT NULL DEFAULT 0,
                    article_count INTEGER NOT NULL DEFAULT 0,
                    articles_downloaded INTEGER NOT NULL DEFAULT 0,
                    articles_failed INTEGER NOT NULL DEFAULT 0,
                    added_at TEXT NOT NULL,
                    completed_at TEXT,
                    work_dir TEXT NOT NULL,
                    output_dir TEXT NOT NULL,
                    password TEXT,
                    error_message TEXT,
                    -- Serialized NzbFile/Article data (bincode)
                    job_data BLOB
                );

                CREATE INDEX IF NOT EXISTS idx_queue_status ON queue(status);
                CREATE INDEX IF NOT EXISTS idx_queue_priority ON queue(priority DESC, added_at ASC);

                -- Completed/failed job history
                CREATE TABLE IF NOT EXISTS history (
                    id TEXT PRIMARY KEY,
                    name TEXT NOT NULL,
                    category TEXT NOT NULL DEFAULT 'Default',
                    status TEXT NOT NULL,
                    total_bytes INTEGER NOT NULL DEFAULT 0,
                    downloaded_bytes INTEGER NOT NULL DEFAULT 0,
                    added_at TEXT NOT NULL,
                    completed_at TEXT NOT NULL,
                    output_dir TEXT NOT NULL,
                    stages TEXT, -- JSON array of StageResult
                    error_message TEXT
                );

                CREATE INDEX IF NOT EXISTS idx_history_completed ON history(completed_at DESC);
                CREATE INDEX IF NOT EXISTS idx_history_status ON history(status);

                -- Server configuration (persisted separately from TOML for runtime changes)
                CREATE TABLE IF NOT EXISTS servers (
                    id TEXT PRIMARY KEY,
                    config TEXT NOT NULL -- JSON ServerConfig
                );

                INSERT INTO schema_version (version) VALUES (1);
                ",
            )?;
        }

        if version < 2 {
            info!("Applying database migration v2");
            self.conn.execute_batch(
                "
                -- Add NZB data storage and server stats to history
                ALTER TABLE history ADD COLUMN nzb_data BLOB;
                ALTER TABLE history ADD COLUMN server_stats TEXT DEFAULT '[]';

                -- Add server stats to queue
                ALTER TABLE queue ADD COLUMN server_stats TEXT DEFAULT '[]';

                -- Add NZB data to queue for preservation
                ALTER TABLE queue ADD COLUMN nzb_raw BLOB;

                UPDATE schema_version SET version = 2;
                ",
            )?;
        }

        if version < 3 {
            info!("Applying database migration v3");
            self.conn.execute_batch(
                "
                -- Per-job log storage for history
                ALTER TABLE history ADD COLUMN job_logs TEXT DEFAULT '[]';

                UPDATE schema_version SET version = 3;
                ",
            )?;
        }

        if version < 4 {
            info!("Applying database migration v4");
            self.conn.execute_batch(
                "
                -- RSS feed items (persistent feed cache)
                CREATE TABLE IF NOT EXISTS rss_items (
                    id TEXT PRIMARY KEY,
                    feed_name TEXT NOT NULL,
                    title TEXT NOT NULL,
                    url TEXT,
                    published_at TEXT,
                    first_seen_at TEXT NOT NULL,
                    downloaded INTEGER NOT NULL DEFAULT 0,
                    downloaded_at TEXT,
                    category TEXT,
                    size_bytes INTEGER DEFAULT 0
                );

                CREATE INDEX IF NOT EXISTS idx_rss_items_feed ON rss_items(feed_name);
                CREATE INDEX IF NOT EXISTS idx_rss_items_seen ON rss_items(first_seen_at DESC);

                -- RSS download rules
                CREATE TABLE IF NOT EXISTS rss_rules (
                    id TEXT PRIMARY KEY,
                    name TEXT NOT NULL,
                    feed_name TEXT NOT NULL,
                    category TEXT,
                    priority INTEGER NOT NULL DEFAULT 1,
                    match_regex TEXT NOT NULL,
                    enabled INTEGER NOT NULL DEFAULT 1
                );

                UPDATE schema_version SET version = 4;
                ",
            )?;
        }

        if version < 5 {
            info!("Applying database migration v5: settings table");
            self.conn.execute_batch(
                "
                CREATE TABLE IF NOT EXISTS settings (
                    key TEXT PRIMARY KEY,
                    value TEXT NOT NULL
                );

                UPDATE schema_version SET version = 5;
                ",
            )?;
        }

        // Ensure settings table exists for databases that jumped to v5
        // with groups tables but without settings (pre-extraction rustnzbd)
        self.conn.execute_batch(
            "CREATE TABLE IF NOT EXISTS settings (
                key TEXT PRIMARY KEY,
                value TEXT NOT NULL
            );",
        )?;

        #[cfg(feature = "groups-db")]
        if version < 6 {
            info!("Applying database migration v6: newsgroup browsing");
            self.conn.execute_batch(
                "
                CREATE TABLE IF NOT EXISTS groups (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL UNIQUE,
                    description TEXT,
                    subscribed INTEGER NOT NULL DEFAULT 0,
                    article_count INTEGER NOT NULL DEFAULT 0,
                    first_article INTEGER NOT NULL DEFAULT 0,
                    last_article INTEGER NOT NULL DEFAULT 0,
                    last_scanned INTEGER NOT NULL DEFAULT 0,
                    last_updated TEXT,
                    created_at TEXT NOT NULL DEFAULT (datetime('now'))
                );
                CREATE INDEX IF NOT EXISTS idx_groups_subscribed ON groups(subscribed);
                CREATE INDEX IF NOT EXISTS idx_groups_name ON groups(name);

                CREATE TABLE IF NOT EXISTS headers (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    group_id INTEGER NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
                    article_num INTEGER NOT NULL,
                    subject TEXT NOT NULL,
                    author TEXT NOT NULL,
                    date TEXT NOT NULL,
                    message_id TEXT NOT NULL,
                    references_ TEXT NOT NULL DEFAULT '',
                    bytes INTEGER NOT NULL DEFAULT 0,
                    lines INTEGER NOT NULL DEFAULT 0,
                    read INTEGER NOT NULL DEFAULT 0,
                    downloaded_at TEXT NOT NULL DEFAULT (datetime('now'))
                );
                CREATE INDEX IF NOT EXISTS idx_headers_group ON headers(group_id);
                CREATE INDEX IF NOT EXISTS idx_headers_msgid ON headers(message_id);
                CREATE INDEX IF NOT EXISTS idx_headers_artnum ON headers(group_id, article_num);

                CREATE VIRTUAL TABLE IF NOT EXISTS headers_fts USING fts5(
                    subject, author, content='headers', content_rowid='id',
                    tokenize='porter unicode61'
                );
                CREATE TRIGGER IF NOT EXISTS headers_fts_ins AFTER INSERT ON headers BEGIN
                    INSERT INTO headers_fts(rowid, subject, author) VALUES (new.id, new.subject, new.author);
                END;
                CREATE TRIGGER IF NOT EXISTS headers_fts_del AFTER DELETE ON headers BEGIN
                    INSERT INTO headers_fts(headers_fts, rowid, subject, author) VALUES ('delete', old.id, old.subject, old.author);
                END;

                UPDATE schema_version SET version = 6;
                ",
            )?;
        }

        Ok(())
    }

    /// Read a setting by key.
    pub fn get_setting(&self, key: &str) -> Option<String> {
        self.conn
            .query_row("SELECT value FROM settings WHERE key = ?1", [key], |row| {
                row.get(0)
            })
            .ok()
    }

    /// Write a setting (upsert).
    pub fn set_setting(&self, key: &str, value: &str) {
        let _ = self.conn.execute(
            "INSERT INTO settings (key, value) VALUES (?1, ?2)
             ON CONFLICT(key) DO UPDATE SET value = ?2",
            [key, value],
        );
    }

    // -----------------------------------------------------------------------
    // Queue operations
    // -----------------------------------------------------------------------

    /// Insert a new job into the queue.
    pub fn queue_insert(&self, job: &NzbJob) -> Result<(), NzbError> {
        self.conn.execute(
            "INSERT INTO queue (id, name, category, status, priority, total_bytes,
             downloaded_bytes, file_count, files_completed, article_count,
             articles_downloaded, articles_failed, added_at, work_dir, output_dir, password)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16)",
            params![
                job.id,
                job.name,
                job.category,
                job.status.to_string(),
                job.priority as i32,
                job.total_bytes as i64,
                job.downloaded_bytes as i64,
                job.file_count as i64,
                job.files_completed as i64,
                job.article_count as i64,
                job.articles_downloaded as i64,
                job.articles_failed as i64,
                job.added_at.to_rfc3339(),
                job.work_dir.to_string_lossy().to_string(),
                job.output_dir.to_string_lossy().to_string(),
                job.password,
            ],
        )?;
        Ok(())
    }

    /// Update job progress in the queue.
    pub fn queue_update_progress(
        &self,
        id: &str,
        status: JobStatus,
        downloaded_bytes: u64,
        articles_downloaded: usize,
        articles_failed: usize,
        files_completed: usize,
    ) -> Result<(), NzbError> {
        self.conn.execute(
            "UPDATE queue SET status=?2, downloaded_bytes=?3, articles_downloaded=?4,
             articles_failed=?5, files_completed=?6 WHERE id=?1",
            params![
                id,
                status.to_string(),
                downloaded_bytes as i64,
                articles_downloaded as i64,
                articles_failed as i64,
                files_completed as i64,
            ],
        )?;
        Ok(())
    }

    /// Update job priority in the queue.
    pub fn queue_update_priority(&self, id: &str, priority: i32) -> Result<(), NzbError> {
        self.conn.execute(
            "UPDATE queue SET priority = ?2 WHERE id = ?1",
            params![id, priority],
        )?;
        Ok(())
    }

    /// Remove a job from the queue.
    pub fn queue_remove(&self, id: &str) -> Result<(), NzbError> {
        self.conn
            .execute("DELETE FROM queue WHERE id=?1", params![id])?;
        Ok(())
    }

    /// List all jobs in the queue, ordered by priority then add time.
    pub fn queue_list(&self) -> Result<Vec<NzbJob>, NzbError> {
        let mut stmt = self.conn.prepare(
            "SELECT id, name, category, status, priority, total_bytes, downloaded_bytes,
             file_count, files_completed, article_count, articles_downloaded, articles_failed,
             added_at, completed_at, work_dir, output_dir, password, error_message
             FROM queue ORDER BY priority DESC, added_at ASC",
        )?;

        let jobs = stmt
            .query_map([], |row| {
                Ok(NzbJob {
                    id: row.get(0)?,
                    name: row.get(1)?,
                    category: row.get(2)?,
                    status: parse_status(&row.get::<_, String>(3)?),
                    priority: parse_priority(row.get::<_, i32>(4)?),
                    total_bytes: row.get::<_, i64>(5)? as u64,
                    downloaded_bytes: row.get::<_, i64>(6)? as u64,
                    file_count: row.get::<_, i64>(7)? as usize,
                    files_completed: row.get::<_, i64>(8)? as usize,
                    article_count: row.get::<_, i64>(9)? as usize,
                    articles_downloaded: row.get::<_, i64>(10)? as usize,
                    articles_failed: row.get::<_, i64>(11)? as usize,
                    added_at: parse_datetime(&row.get::<_, String>(12)?),
                    completed_at: row
                        .get::<_, Option<String>>(13)?
                        .map(|s| parse_datetime(&s)),
                    work_dir: row.get::<_, String>(14)?.into(),
                    output_dir: row.get::<_, String>(15)?.into(),
                    password: row.get(16)?,
                    error_message: row.get(17)?,
                    speed_bps: 0,
                    server_stats: Vec::new(),
                    files: Vec::new(), // Loaded separately
                })
            })?
            .collect::<Result<Vec<_>, _>>()?;

        Ok(jobs)
    }

    // -----------------------------------------------------------------------
    // History operations
    // -----------------------------------------------------------------------

    /// Move a completed/failed job to history.
    pub fn history_insert(&self, entry: &HistoryEntry) -> Result<(), NzbError> {
        let stages_json = serde_json::to_string(&entry.stages).unwrap_or_default();
        let server_stats_json = serde_json::to_string(&entry.server_stats).unwrap_or_default();
        self.conn.execute(
            "INSERT INTO history (id, name, category, status, total_bytes, downloaded_bytes,
             added_at, completed_at, output_dir, stages, error_message, nzb_data, server_stats)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)",
            params![
                entry.id,
                entry.name,
                entry.category,
                entry.status.to_string(),
                entry.total_bytes as i64,
                entry.downloaded_bytes as i64,
                entry.added_at.to_rfc3339(),
                entry.completed_at.to_rfc3339(),
                entry.output_dir.to_string_lossy().to_string(),
                stages_json,
                entry.error_message,
                entry.nzb_data,
                server_stats_json,
            ],
        )?;
        Ok(())
    }

    /// List history entries, most recent first.
    pub fn history_list(&self, limit: usize) -> Result<Vec<HistoryEntry>, NzbError> {
        let mut stmt = self.conn.prepare(
            "SELECT id, name, category, status, total_bytes, downloaded_bytes,
             added_at, completed_at, output_dir, stages, error_message, server_stats,
             CASE WHEN nzb_data IS NOT NULL THEN 1 ELSE 0 END as has_nzb
             FROM history ORDER BY completed_at DESC LIMIT ?1",
        )?;

        let entries = stmt
            .query_map(params![limit as i64], |row| {
                let stages_json: String = row.get::<_, Option<String>>(9)?.unwrap_or_default();
                let stages: Vec<StageResult> =
                    serde_json::from_str(&stages_json).unwrap_or_default();
                let stats_json: String = row.get::<_, Option<String>>(11)?.unwrap_or_default();
                let server_stats: Vec<ServerArticleStats> =
                    serde_json::from_str(&stats_json).unwrap_or_default();
                let has_nzb: i64 = row.get(12)?;

                Ok(HistoryEntry {
                    id: row.get(0)?,
                    name: row.get(1)?,
                    category: row.get(2)?,
                    status: parse_status(&row.get::<_, String>(3)?),
                    total_bytes: row.get::<_, i64>(4)? as u64,
                    downloaded_bytes: row.get::<_, i64>(5)? as u64,
                    added_at: parse_datetime(&row.get::<_, String>(6)?),
                    completed_at: parse_datetime(&row.get::<_, String>(7)?),
                    output_dir: row.get::<_, String>(8)?.into(),
                    stages,
                    error_message: row.get(10)?,
                    server_stats,
                    // Don't load actual blob in list - just note if it exists
                    nzb_data: if has_nzb != 0 { Some(Vec::new()) } else { None },
                })
            })?
            .collect::<Result<Vec<_>, _>>()?;

        Ok(entries)
    }

    /// Get the raw NZB data for a history entry (for retry).
    pub fn history_get_nzb_data(&self, id: &str) -> Result<Option<Vec<u8>>, NzbError> {
        let result = self.conn.query_row(
            "SELECT nzb_data FROM history WHERE id = ?1",
            params![id],
            |row| row.get::<_, Option<Vec<u8>>>(0),
        );
        match result {
            Ok(data) => Ok(data),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(NzbError::Database(e)),
        }
    }

    /// Enforce history retention limit by deleting oldest entries.
    pub fn history_enforce_retention(&self, max_entries: usize) -> Result<(), NzbError> {
        self.conn.execute(
            "DELETE FROM history WHERE id NOT IN (
                SELECT id FROM history ORDER BY completed_at DESC LIMIT ?1
            )",
            params![max_entries as i64],
        )?;
        Ok(())
    }

    /// Get a single history entry by ID.
    pub fn history_get(&self, id: &str) -> Result<Option<HistoryEntry>, NzbError> {
        let mut stmt = self.conn.prepare(
            "SELECT id, name, category, status, total_bytes, downloaded_bytes,
             added_at, completed_at, output_dir, stages, error_message, server_stats
             FROM history WHERE id = ?1",
        )?;

        let result = stmt.query_row(params![id], |row| {
            let stages_json: String = row.get::<_, Option<String>>(9)?.unwrap_or_default();
            let stages: Vec<StageResult> = serde_json::from_str(&stages_json).unwrap_or_default();
            let stats_json: String = row.get::<_, Option<String>>(11)?.unwrap_or_default();
            let server_stats: Vec<ServerArticleStats> =
                serde_json::from_str(&stats_json).unwrap_or_default();

            Ok(HistoryEntry {
                id: row.get(0)?,
                name: row.get(1)?,
                category: row.get(2)?,
                status: parse_status(&row.get::<_, String>(3)?),
                total_bytes: row.get::<_, i64>(4)? as u64,
                downloaded_bytes: row.get::<_, i64>(5)? as u64,
                added_at: parse_datetime(&row.get::<_, String>(6)?),
                completed_at: parse_datetime(&row.get::<_, String>(7)?),
                output_dir: row.get::<_, String>(8)?.into(),
                stages,
                error_message: row.get(10)?,
                server_stats,
                nzb_data: None,
            })
        });

        match result {
            Ok(entry) => Ok(Some(entry)),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(NzbError::Database(e)),
        }
    }

    /// Store serialized job file/article state for resume support.
    pub fn queue_store_job_data(&self, id: &str, data: &[u8]) -> Result<(), NzbError> {
        self.conn.execute(
            "UPDATE queue SET job_data = ?2 WHERE id = ?1",
            params![id, data],
        )?;
        Ok(())
    }

    /// Load serialized job file/article state for resume.
    pub fn queue_load_job_data(&self, id: &str) -> Result<Option<Vec<u8>>, NzbError> {
        let mut stmt = self
            .conn
            .prepare("SELECT job_data FROM queue WHERE id = ?1")?;
        let result = stmt.query_row(params![id], |row| row.get::<_, Option<Vec<u8>>>(0))?;
        Ok(result)
    }

    /// Store raw NZB data for a queue job.
    pub fn queue_store_nzb_data(&self, id: &str, nzb_data: &[u8]) -> Result<(), NzbError> {
        self.conn.execute(
            "UPDATE queue SET nzb_raw = ?2 WHERE id = ?1",
            params![id, nzb_data],
        )?;
        Ok(())
    }

    /// Get raw NZB data from a queue job.
    pub fn queue_get_nzb_data(&self, id: &str) -> Result<Option<Vec<u8>>, NzbError> {
        let result = self.conn.query_row(
            "SELECT nzb_raw FROM queue WHERE id = ?1",
            params![id],
            |row| row.get::<_, Option<Vec<u8>>>(0),
        );
        match result {
            Ok(data) => Ok(data),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(NzbError::Database(e)),
        }
    }

    /// Count history entries.
    pub fn history_count(&self) -> Result<usize, NzbError> {
        let count: i64 = self
            .conn
            .query_row("SELECT COUNT(*) FROM history", [], |row| row.get(0))?;
        Ok(count as usize)
    }

    /// Remove a history entry.
    pub fn history_remove(&self, id: &str) -> Result<(), NzbError> {
        self.conn
            .execute("DELETE FROM history WHERE id=?1", params![id])?;
        Ok(())
    }

    /// Clear all history.
    pub fn history_clear(&self) -> Result<(), NzbError> {
        self.conn.execute("DELETE FROM history", [])?;
        Ok(())
    }

    /// Store per-job logs for a history entry.
    pub fn history_store_logs(&self, id: &str, logs_json: &str) -> Result<(), NzbError> {
        self.conn.execute(
            "UPDATE history SET job_logs = ?2 WHERE id = ?1",
            params![id, logs_json],
        )?;
        Ok(())
    }

    /// Get per-job logs for a history entry.
    pub fn history_get_logs(&self, id: &str) -> Result<Option<String>, NzbError> {
        let result = self.conn.query_row(
            "SELECT job_logs FROM history WHERE id = ?1",
            params![id],
            |row| row.get::<_, Option<String>>(0),
        );
        match result {
            Ok(data) => Ok(data),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(NzbError::Database(e)),
        }
    }

    // -----------------------------------------------------------------------
    // RSS item operations
    // -----------------------------------------------------------------------

    /// Upsert an RSS feed item (insert or ignore if already exists).
    pub fn rss_item_upsert(&self, item: &RssItem) -> Result<(), NzbError> {
        self.conn.execute(
            "INSERT OR IGNORE INTO rss_items (id, feed_name, title, url, published_at,
             first_seen_at, downloaded, downloaded_at, category, size_bytes)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
            params![
                item.id,
                item.feed_name,
                item.title,
                item.url,
                item.published_at.map(|d| d.to_rfc3339()),
                item.first_seen_at.to_rfc3339(),
                item.downloaded as i32,
                item.downloaded_at.map(|d| d.to_rfc3339()),
                item.category,
                item.size_bytes as i64,
            ],
        )?;
        Ok(())
    }

    /// Batch upsert RSS feed items in a single transaction.
    /// Returns the number of newly inserted items.
    pub fn rss_items_batch_upsert(&self, items: &[RssItem]) -> Result<usize, NzbError> {
        let tx = self.conn.unchecked_transaction()?;
        let mut inserted = 0usize;
        {
            let mut stmt = tx.prepare_cached(
                "INSERT OR IGNORE INTO rss_items (id, feed_name, title, url, published_at,
                 first_seen_at, downloaded, downloaded_at, category, size_bytes)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
            )?;
            for item in items {
                let rows = stmt.execute(params![
                    item.id,
                    item.feed_name,
                    item.title,
                    item.url,
                    item.published_at.map(|d| d.to_rfc3339()),
                    item.first_seen_at.to_rfc3339(),
                    item.downloaded as i32,
                    item.downloaded_at.map(|d| d.to_rfc3339()),
                    item.category,
                    item.size_bytes as i64,
                ])?;
                if rows > 0 {
                    inserted += 1;
                }
            }
        }
        tx.commit()?;
        Ok(inserted)
    }

    /// Check if an RSS item ID already exists in the database.
    pub fn rss_item_exists(&self, id: &str) -> Result<bool, NzbError> {
        let count: i64 = self.conn.query_row(
            "SELECT COUNT(*) FROM rss_items WHERE id = ?1",
            params![id],
            |row| row.get(0),
        )?;
        Ok(count > 0)
    }

    /// List RSS items, optionally filtered by feed name, ordered by first_seen_at DESC.
    pub fn rss_items_list(
        &self,
        feed_name: Option<&str>,
        limit: usize,
    ) -> Result<Vec<RssItem>, NzbError> {
        let (sql, limit_val) = if let Some(name) = feed_name {
            let mut stmt = self.conn.prepare(
                "SELECT id, feed_name, title, url, published_at, first_seen_at,
                 downloaded, downloaded_at, category, size_bytes
                 FROM rss_items WHERE feed_name = ?1
                 ORDER BY first_seen_at DESC LIMIT ?2",
            )?;
            let items = stmt
                .query_map(params![name, limit as i64], |row| self.map_rss_item(row))?
                .collect::<Result<Vec<_>, _>>()?;
            return Ok(items);
        } else {
            (
                "SELECT id, feed_name, title, url, published_at, first_seen_at,
                 downloaded, downloaded_at, category, size_bytes
                 FROM rss_items ORDER BY first_seen_at DESC LIMIT ?1",
                limit,
            )
        };
        let mut stmt = self.conn.prepare(sql)?;
        let items = stmt
            .query_map(params![limit_val as i64], |row| self.map_rss_item(row))?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(items)
    }

    /// Get a single RSS item by ID.
    pub fn rss_item_get(&self, id: &str) -> Result<Option<RssItem>, NzbError> {
        let mut stmt = self.conn.prepare(
            "SELECT id, feed_name, title, url, published_at, first_seen_at,
             downloaded, downloaded_at, category, size_bytes
             FROM rss_items WHERE id = ?1",
        )?;
        let result = stmt.query_row(params![id], |row| self.map_rss_item(row));
        match result {
            Ok(item) => Ok(Some(item)),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(NzbError::Database(e)),
        }
    }

    /// Mark an RSS item as downloaded.
    pub fn rss_item_mark_downloaded(
        &self,
        id: &str,
        category: Option<&str>,
    ) -> Result<(), NzbError> {
        self.conn.execute(
            "UPDATE rss_items SET downloaded = 1, downloaded_at = ?2, category = ?3 WHERE id = ?1",
            params![id, Utc::now().to_rfc3339(), category],
        )?;
        Ok(())
    }

    /// Count total RSS items.
    pub fn rss_item_count(&self) -> Result<usize, NzbError> {
        let count: i64 = self
            .conn
            .query_row("SELECT COUNT(*) FROM rss_items", [], |row| row.get(0))?;
        Ok(count as usize)
    }

    /// Prune RSS items to keep only the N most recent (by first_seen_at).
    pub fn rss_items_prune(&self, keep: usize) -> Result<usize, NzbError> {
        let deleted = self.conn.execute(
            "DELETE FROM rss_items WHERE id NOT IN (
                SELECT id FROM rss_items ORDER BY first_seen_at DESC LIMIT ?1
            )",
            params![keep as i64],
        )?;
        Ok(deleted)
    }

    fn map_rss_item(&self, row: &rusqlite::Row<'_>) -> rusqlite::Result<RssItem> {
        Ok(RssItem {
            id: row.get(0)?,
            feed_name: row.get(1)?,
            title: row.get(2)?,
            url: row.get(3)?,
            published_at: row.get::<_, Option<String>>(4)?.map(|s| parse_datetime(&s)),
            first_seen_at: parse_datetime(&row.get::<_, String>(5)?),
            downloaded: row.get::<_, i32>(6)? != 0,
            downloaded_at: row.get::<_, Option<String>>(7)?.map(|s| parse_datetime(&s)),
            category: row.get(8)?,
            size_bytes: row.get::<_, i64>(9)? as u64,
        })
    }

    // -----------------------------------------------------------------------
    // RSS rule operations
    // -----------------------------------------------------------------------

    /// Insert a new RSS download rule.
    /// feed_names is stored as comma-separated string in the DB.
    pub fn rss_rule_insert(&self, rule: &RssRule) -> Result<(), NzbError> {
        let feed_names_str = rule.feed_names.join(",");
        self.conn.execute(
            "INSERT INTO rss_rules (id, name, feed_name, category, priority, match_regex, enabled)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
            params![
                rule.id,
                rule.name,
                feed_names_str,
                rule.category,
                rule.priority,
                rule.match_regex,
                rule.enabled as i32,
            ],
        )?;
        Ok(())
    }

    /// List all RSS download rules.
    pub fn rss_rule_list(&self) -> Result<Vec<RssRule>, NzbError> {
        let mut stmt = self.conn.prepare(
            "SELECT id, name, feed_name, category, priority, match_regex, enabled
             FROM rss_rules ORDER BY name ASC",
        )?;
        let rules = stmt
            .query_map([], |row| {
                let feed_names_str: String = row.get(2)?;
                let feed_names: Vec<String> = feed_names_str
                    .split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                    .collect();
                Ok(RssRule {
                    id: row.get(0)?,
                    name: row.get(1)?,
                    feed_names,
                    category: row.get(3)?,
                    priority: row.get(4)?,
                    match_regex: row.get(5)?,
                    enabled: row.get::<_, i32>(6)? != 0,
                })
            })?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(rules)
    }

    /// Update an RSS download rule.
    pub fn rss_rule_update(&self, rule: &RssRule) -> Result<(), NzbError> {
        let feed_names_str = rule.feed_names.join(",");
        self.conn.execute(
            "UPDATE rss_rules SET name=?2, feed_name=?3, category=?4, priority=?5,
             match_regex=?6, enabled=?7 WHERE id=?1",
            params![
                rule.id,
                rule.name,
                feed_names_str,
                rule.category,
                rule.priority,
                rule.match_regex,
                rule.enabled as i32,
            ],
        )?;
        Ok(())
    }

    /// Delete an RSS download rule.
    pub fn rss_rule_delete(&self, id: &str) -> Result<(), NzbError> {
        self.conn
            .execute("DELETE FROM rss_rules WHERE id=?1", params![id])?;
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Parse helpers
// ---------------------------------------------------------------------------

fn parse_status(s: &str) -> JobStatus {
    match s.to_lowercase().as_str() {
        "queued" => JobStatus::Queued,
        "downloading" => JobStatus::Downloading,
        "paused" => JobStatus::Paused,
        "verifying" => JobStatus::Verifying,
        "repairing" => JobStatus::Repairing,
        "extracting" => JobStatus::Extracting,
        "postprocessing" => JobStatus::PostProcessing,
        "completed" => JobStatus::Completed,
        "failed" => JobStatus::Failed,
        _ => JobStatus::Queued,
    }
}

fn parse_priority(v: i32) -> Priority {
    match v {
        0 => Priority::Low,
        1 => Priority::Normal,
        2 => Priority::High,
        3 => Priority::Force,
        _ => Priority::Normal,
    }
}

fn parse_datetime(s: &str) -> chrono::DateTime<Utc> {
    chrono::DateTime::parse_from_rfc3339(s)
        .map(|dt| dt.with_timezone(&Utc))
        .unwrap_or_else(|_| Utc::now())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_job(id: &str, name: &str) -> NzbJob {
        NzbJob {
            id: id.into(),
            name: name.into(),
            category: "Default".into(),
            status: JobStatus::Queued,
            priority: Priority::Normal,
            total_bytes: 1_000_000,
            downloaded_bytes: 0,
            file_count: 3,
            files_completed: 0,
            article_count: 30,
            articles_downloaded: 0,
            articles_failed: 0,
            added_at: Utc::now(),
            completed_at: None,
            work_dir: "/tmp/test".into(),
            output_dir: "/downloads/test".into(),
            password: None,
            error_message: None,
            speed_bps: 0,
            server_stats: Vec::new(),
            files: Vec::new(),
        }
    }

    fn make_history(id: &str, name: &str) -> HistoryEntry {
        HistoryEntry {
            id: id.into(),
            name: name.into(),
            category: "movies".into(),
            status: JobStatus::Completed,
            total_bytes: 5_000_000,
            downloaded_bytes: 5_000_000,
            added_at: Utc::now(),
            completed_at: Utc::now(),
            output_dir: "/downloads/complete".into(),
            stages: vec![StageResult {
                name: "Verify".into(),
                status: StageStatus::Success,
                message: None,
                duration_secs: 2.5,
            }],
            error_message: None,
            server_stats: Vec::new(),
            nzb_data: None,
        }
    }

    fn make_rss_item(id: &str, feed: &str, title: &str) -> RssItem {
        RssItem {
            id: id.into(),
            feed_name: feed.into(),
            title: title.into(),
            url: Some("https://example.com/nzb".into()),
            published_at: Some(Utc::now()),
            first_seen_at: Utc::now(),
            downloaded: false,
            downloaded_at: None,
            category: None,
            size_bytes: 1_000_000,
        }
    }

    // -----------------------------------------------------------------------
    // Schema & migration
    // -----------------------------------------------------------------------

    #[test]
    fn test_db_create_and_migrate() {
        let db = Database::open_memory().unwrap();
        let jobs = db.queue_list().unwrap();
        assert!(jobs.is_empty());
    }

    // -----------------------------------------------------------------------
    // Queue operations
    // -----------------------------------------------------------------------

    #[test]
    fn test_queue_insert_and_list() {
        let db = Database::open_memory().unwrap();
        let job = make_job("test-123", "Test Download");

        db.queue_insert(&job).unwrap();
        let jobs = db.queue_list().unwrap();
        assert_eq!(jobs.len(), 1);
        assert_eq!(jobs[0].name, "Test Download");
        assert_eq!(jobs[0].total_bytes, 1_000_000);
    }

    #[test]
    fn test_queue_update_progress() {
        let db = Database::open_memory().unwrap();
        db.queue_insert(&make_job("q1", "Job 1")).unwrap();

        db.queue_update_progress("q1", JobStatus::Downloading, 500_000, 15, 2, 1)
            .unwrap();

        let jobs = db.queue_list().unwrap();
        assert_eq!(jobs[0].status, JobStatus::Downloading);
        assert_eq!(jobs[0].downloaded_bytes, 500_000);
        assert_eq!(jobs[0].articles_downloaded, 15);
        assert_eq!(jobs[0].articles_failed, 2);
        assert_eq!(jobs[0].files_completed, 1);
    }

    #[test]
    fn test_queue_update_priority() {
        let db = Database::open_memory().unwrap();
        db.queue_insert(&make_job("q2", "Job 2")).unwrap();

        db.queue_update_priority("q2", 3).unwrap();

        let jobs = db.queue_list().unwrap();
        assert_eq!(jobs[0].priority, Priority::Force);
    }

    #[test]
    fn test_queue_remove() {
        let db = Database::open_memory().unwrap();
        db.queue_insert(&make_job("q3", "Job 3")).unwrap();
        assert_eq!(db.queue_list().unwrap().len(), 1);

        db.queue_remove("q3").unwrap();
        assert_eq!(db.queue_list().unwrap().len(), 0);
    }

    #[test]
    fn test_queue_ordering() {
        let db = Database::open_memory().unwrap();

        let mut low = make_job("low", "Low Priority");
        low.priority = Priority::Low;
        let mut high = make_job("high", "High Priority");
        high.priority = Priority::High;
        let normal = make_job("normal", "Normal Priority");

        db.queue_insert(&low).unwrap();
        db.queue_insert(&high).unwrap();
        db.queue_insert(&normal).unwrap();

        let jobs = db.queue_list().unwrap();
        assert_eq!(jobs[0].id, "high");
        assert_eq!(jobs[1].id, "normal");
        assert_eq!(jobs[2].id, "low");
    }

    #[test]
    fn test_queue_store_and_load_job_data() {
        let db = Database::open_memory().unwrap();
        db.queue_insert(&make_job("jd1", "Job Data")).unwrap();

        let blob = vec![1u8, 2, 3, 4, 5, 6, 7, 8];
        db.queue_store_job_data("jd1", &blob).unwrap();

        let loaded = db.queue_load_job_data("jd1").unwrap();
        assert_eq!(loaded, Some(blob));
    }

    #[test]
    fn test_queue_load_job_data_empty() {
        let db = Database::open_memory().unwrap();
        db.queue_insert(&make_job("jd2", "No Data")).unwrap();

        let loaded = db.queue_load_job_data("jd2").unwrap();
        assert!(loaded.is_none());
    }

    #[test]
    fn test_queue_store_and_get_nzb_data() {
        let db = Database::open_memory().unwrap();
        db.queue_insert(&make_job("nzb1", "NZB Store")).unwrap();

        let nzb = b"<nzb>...</nzb>".to_vec();
        db.queue_store_nzb_data("nzb1", &nzb).unwrap();

        let loaded = db.queue_get_nzb_data("nzb1").unwrap();
        assert_eq!(loaded, Some(nzb));
    }

    #[test]
    fn test_queue_get_nzb_data_nonexistent() {
        let db = Database::open_memory().unwrap();
        let result = db.queue_get_nzb_data("nonexistent").unwrap();
        assert!(result.is_none());
    }

    // -----------------------------------------------------------------------
    // History operations
    // -----------------------------------------------------------------------

    #[test]
    fn test_history_insert_and_list() {
        let db = Database::open_memory().unwrap();
        let entry = make_history("hist-1", "Completed Job");

        db.history_insert(&entry).unwrap();
        let history = db.history_list(10).unwrap();
        assert_eq!(history.len(), 1);
        assert_eq!(history[0].name, "Completed Job");
        assert_eq!(history[0].stages.len(), 1);
    }

    #[test]
    fn test_history_get_by_id() {
        let db = Database::open_memory().unwrap();
        db.history_insert(&make_history("h1", "History 1")).unwrap();

        let entry = db.history_get("h1").unwrap();
        assert!(entry.is_some());
        assert_eq!(entry.unwrap().name, "History 1");
    }

    #[test]
    fn test_history_get_nonexistent() {
        let db = Database::open_memory().unwrap();
        let entry = db.history_get("nonexistent").unwrap();
        assert!(entry.is_none());
    }

    #[test]
    fn test_history_get_nzb_data() {
        let db = Database::open_memory().unwrap();
        let mut entry = make_history("h-nzb", "With NZB");
        entry.nzb_data = Some(b"<nzb>data</nzb>".to_vec());
        db.history_insert(&entry).unwrap();

        let data = db.history_get_nzb_data("h-nzb").unwrap();
        assert!(data.is_some());
        assert_eq!(data.unwrap(), b"<nzb>data</nzb>");
    }

    #[test]
    fn test_history_get_nzb_data_nonexistent() {
        let db = Database::open_memory().unwrap();
        let data = db.history_get_nzb_data("missing").unwrap();
        assert!(data.is_none());
    }

    #[test]
    fn test_history_count() {
        let db = Database::open_memory().unwrap();
        assert_eq!(db.history_count().unwrap(), 0);

        db.history_insert(&make_history("hc1", "Job 1")).unwrap();
        db.history_insert(&make_history("hc2", "Job 2")).unwrap();
        db.history_insert(&make_history("hc3", "Job 3")).unwrap();
        assert_eq!(db.history_count().unwrap(), 3);
    }

    #[test]
    fn test_history_remove() {
        let db = Database::open_memory().unwrap();
        db.history_insert(&make_history("hr1", "To Remove"))
            .unwrap();
        assert_eq!(db.history_count().unwrap(), 1);

        db.history_remove("hr1").unwrap();
        assert_eq!(db.history_count().unwrap(), 0);
    }

    #[test]
    fn test_history_clear() {
        let db = Database::open_memory().unwrap();
        db.history_insert(&make_history("hcl1", "Job 1")).unwrap();
        db.history_insert(&make_history("hcl2", "Job 2")).unwrap();
        assert_eq!(db.history_count().unwrap(), 2);

        db.history_clear().unwrap();
        assert_eq!(db.history_count().unwrap(), 0);
    }

    #[test]
    fn test_history_enforce_retention() {
        let db = Database::open_memory().unwrap();
        for i in 0..5 {
            db.history_insert(&make_history(&format!("ret-{i}"), &format!("Job {i}")))
                .unwrap();
        }
        assert_eq!(db.history_count().unwrap(), 5);

        db.history_enforce_retention(3).unwrap();
        assert_eq!(db.history_count().unwrap(), 3);
    }

    #[test]
    fn test_history_store_and_get_logs() {
        let db = Database::open_memory().unwrap();
        db.history_insert(&make_history("hl1", "With Logs"))
            .unwrap();

        let logs = r#"[{"ts":"2024-01-01","msg":"Started"}]"#;
        db.history_store_logs("hl1", logs).unwrap();

        let loaded = db.history_get_logs("hl1").unwrap();
        assert_eq!(loaded.as_deref(), Some(logs));
    }

    #[test]
    fn test_history_get_logs_nonexistent() {
        let db = Database::open_memory().unwrap();
        let result = db.history_get_logs("missing").unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_history_with_server_stats() {
        let db = Database::open_memory().unwrap();
        let mut entry = make_history("hss", "Stats Job");
        entry.server_stats = vec![ServerArticleStats {
            server_id: "srv-1".into(),
            server_name: "Provider".into(),
            articles_downloaded: 100,
            articles_failed: 5,
            bytes_downloaded: 75_000_000,
        }];
        db.history_insert(&entry).unwrap();

        let loaded = db.history_list(10).unwrap();
        assert_eq!(loaded[0].server_stats.len(), 1);
        assert_eq!(loaded[0].server_stats[0].server_id, "srv-1");
        assert_eq!(loaded[0].server_stats[0].articles_downloaded, 100);
    }

    // -----------------------------------------------------------------------
    // RSS item operations
    // -----------------------------------------------------------------------

    #[test]
    fn test_rss_item_upsert_and_get() {
        let db = Database::open_memory().unwrap();
        let item = make_rss_item("rss-1", "feed-a", "Test Title");
        db.rss_item_upsert(&item).unwrap();

        let loaded = db.rss_item_get("rss-1").unwrap();
        assert!(loaded.is_some());
        let loaded = loaded.unwrap();
        assert_eq!(loaded.title, "Test Title");
        assert_eq!(loaded.feed_name, "feed-a");
        assert!(!loaded.downloaded);
    }

    #[test]
    fn test_rss_item_upsert_ignores_duplicate() {
        let db = Database::open_memory().unwrap();
        let item = make_rss_item("dup-1", "feed-a", "Original");
        db.rss_item_upsert(&item).unwrap();

        // Upsert again with different title — should be ignored (INSERT OR IGNORE)
        let item2 = make_rss_item("dup-1", "feed-a", "Updated");
        db.rss_item_upsert(&item2).unwrap();

        let loaded = db.rss_item_get("dup-1").unwrap().unwrap();
        assert_eq!(loaded.title, "Original"); // Not updated
    }

    #[test]
    fn test_rss_item_exists() {
        let db = Database::open_memory().unwrap();
        assert!(!db.rss_item_exists("rss-x").unwrap());

        db.rss_item_upsert(&make_rss_item("rss-x", "feed", "Title"))
            .unwrap();
        assert!(db.rss_item_exists("rss-x").unwrap());
    }

    #[test]
    fn test_rss_items_batch_upsert() {
        let db = Database::open_memory().unwrap();
        let items = vec![
            make_rss_item("b1", "feed-a", "Title 1"),
            make_rss_item("b2", "feed-a", "Title 2"),
            make_rss_item("b3", "feed-b", "Title 3"),
        ];

        let inserted = db.rss_items_batch_upsert(&items).unwrap();
        assert_eq!(inserted, 3);
        assert_eq!(db.rss_item_count().unwrap(), 3);

        // Batch again — duplicates ignored
        let inserted2 = db.rss_items_batch_upsert(&items).unwrap();
        assert_eq!(inserted2, 0);
        assert_eq!(db.rss_item_count().unwrap(), 3);
    }

    #[test]
    fn test_rss_items_list_all() {
        let db = Database::open_memory().unwrap();
        db.rss_item_upsert(&make_rss_item("la1", "feed-a", "A1"))
            .unwrap();
        db.rss_item_upsert(&make_rss_item("la2", "feed-b", "B1"))
            .unwrap();

        let items = db.rss_items_list(None, 100).unwrap();
        assert_eq!(items.len(), 2);
    }

    #[test]
    fn test_rss_items_list_filtered() {
        let db = Database::open_memory().unwrap();
        db.rss_item_upsert(&make_rss_item("lf1", "feed-a", "A Item"))
            .unwrap();
        db.rss_item_upsert(&make_rss_item("lf2", "feed-b", "B Item"))
            .unwrap();
        db.rss_item_upsert(&make_rss_item("lf3", "feed-a", "A Item 2"))
            .unwrap();

        let items = db.rss_items_list(Some("feed-a"), 100).unwrap();
        assert_eq!(items.len(), 2);
        for item in &items {
            assert_eq!(item.feed_name, "feed-a");
        }
    }

    #[test]
    fn test_rss_item_mark_downloaded() {
        let db = Database::open_memory().unwrap();
        db.rss_item_upsert(&make_rss_item("md1", "feed", "Title"))
            .unwrap();

        db.rss_item_mark_downloaded("md1", Some("movies")).unwrap();

        let loaded = db.rss_item_get("md1").unwrap().unwrap();
        assert!(loaded.downloaded);
        assert!(loaded.downloaded_at.is_some());
        assert_eq!(loaded.category.as_deref(), Some("movies"));
    }

    #[test]
    fn test_rss_item_count() {
        let db = Database::open_memory().unwrap();
        assert_eq!(db.rss_item_count().unwrap(), 0);

        db.rss_item_upsert(&make_rss_item("c1", "f", "T1")).unwrap();
        db.rss_item_upsert(&make_rss_item("c2", "f", "T2")).unwrap();
        assert_eq!(db.rss_item_count().unwrap(), 2);
    }

    #[test]
    fn test_rss_items_prune() {
        let db = Database::open_memory().unwrap();
        for i in 0..10 {
            db.rss_item_upsert(&make_rss_item(&format!("pr-{i}"), "f", &format!("T{i}")))
                .unwrap();
        }
        assert_eq!(db.rss_item_count().unwrap(), 10);

        let deleted = db.rss_items_prune(5).unwrap();
        assert_eq!(deleted, 5);
        assert_eq!(db.rss_item_count().unwrap(), 5);
    }

    // -----------------------------------------------------------------------
    // RSS rule operations
    // -----------------------------------------------------------------------

    #[test]
    fn test_rss_rule_insert_and_list() {
        let db = Database::open_memory().unwrap();
        let rule = RssRule {
            id: "rule-1".into(),
            name: "Movies".into(),
            feed_names: vec!["feed-a".into(), "feed-b".into()],
            category: Some("movies".into()),
            priority: 2,
            match_regex: ".*1080p.*".into(),
            enabled: true,
        };

        db.rss_rule_insert(&rule).unwrap();
        let rules = db.rss_rule_list().unwrap();
        assert_eq!(rules.len(), 1);
        assert_eq!(rules[0].name, "Movies");
        assert_eq!(rules[0].feed_names, vec!["feed-a", "feed-b"]);
        assert_eq!(rules[0].match_regex, ".*1080p.*");
        assert!(rules[0].enabled);
    }

    #[test]
    fn test_rss_rule_update() {
        let db = Database::open_memory().unwrap();
        let rule = RssRule {
            id: "rule-u".into(),
            name: "Original".into(),
            feed_names: vec!["feed-a".into()],
            category: None,
            priority: 1,
            match_regex: ".*".into(),
            enabled: true,
        };
        db.rss_rule_insert(&rule).unwrap();

        let updated = RssRule {
            id: "rule-u".into(),
            name: "Updated".into(),
            feed_names: vec!["feed-a".into(), "feed-c".into()],
            category: Some("tv".into()),
            priority: 3,
            match_regex: ".*2160p.*".into(),
            enabled: false,
        };
        db.rss_rule_update(&updated).unwrap();

        let rules = db.rss_rule_list().unwrap();
        assert_eq!(rules[0].name, "Updated");
        assert_eq!(rules[0].feed_names, vec!["feed-a", "feed-c"]);
        assert_eq!(rules[0].category.as_deref(), Some("tv"));
        assert!(!rules[0].enabled);
    }

    #[test]
    fn test_rss_rule_delete() {
        let db = Database::open_memory().unwrap();
        let rule = RssRule {
            id: "rule-d".into(),
            name: "Delete Me".into(),
            feed_names: vec!["f".into()],
            category: None,
            priority: 1,
            match_regex: ".*".into(),
            enabled: true,
        };
        db.rss_rule_insert(&rule).unwrap();
        assert_eq!(db.rss_rule_list().unwrap().len(), 1);

        db.rss_rule_delete("rule-d").unwrap();
        assert_eq!(db.rss_rule_list().unwrap().len(), 0);
    }

    #[test]
    fn test_settings_get_set() {
        let db = Database::open_memory().unwrap();
        db.set_setting("theme", "dark");
        assert_eq!(db.get_setting("theme"), Some("dark".to_string()));
    }

    #[test]
    fn test_settings_upsert() {
        let db = Database::open_memory().unwrap();
        db.set_setting("speed", "100");
        db.set_setting("speed", "200");
        assert_eq!(db.get_setting("speed"), Some("200".to_string()));
    }

    #[test]
    fn test_settings_missing_key() {
        let db = Database::open_memory().unwrap();
        assert_eq!(db.get_setting("nonexistent"), None);
    }
}