d-engine-core 0.2.3

Pure Raft consensus algorithm - for building custom Raft-based systems
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
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
//! Unit tests for ElectionHandler implementing core Raft leader election protocol (Section 5.2)
//!
//! These tests verify:
//! - Vote request validation and granting logic
//! - Majority quorum calculation
//! - Log recency checks
//! - Term advancement and state transitions
//! - Edge cases in election rules

use std::sync::Arc;

use d_engine_proto::common::LogId;
use d_engine_proto::server::election::VoteRequest;
use d_engine_proto::server::election::VotedFor;

use crate::MockRaftLog;
use crate::MockTypeConfig;
use crate::election::ElectionCore;
use crate::election::ElectionHandler;

// ============================================================================
// Helper Functions
// ============================================================================

fn create_handler(node_id: u32) -> ElectionHandler<MockTypeConfig> {
    ElectionHandler::new(node_id)
}

fn create_vote_request(
    term: u64,
    candidate_id: u32,
    last_log_index: u64,
    last_log_term: u64,
) -> VoteRequest {
    VoteRequest {
        term,
        candidate_id,
        last_log_index,
        last_log_term,
    }
}

fn create_mock_raft_log(last_log_id: Option<LogId>) -> MockRaftLog {
    let mut raft_log = MockRaftLog::new();
    raft_log.expect_last_log_id().returning(move || last_log_id);
    raft_log
}

// ============================================================================
// test_handle_vote_request_* - Vote Request Handling
// ============================================================================

/// Test: Voter grants vote when candidate has higher term and valid log
///
/// Scenario:
/// - Current term: 1
/// - Request term: 2 (higher)
/// - Local log: index=1, term=1
/// - Candidate log: index=2, term=2 (more recent)
/// - Voted for: None
///
/// Expected: Vote granted, term updated
#[tokio::test]
async fn test_handle_vote_request_grant_higher_term() {
    // Arrange
    let handler = create_handler(2);
    let request = create_vote_request(2, 1, 2, 2);
    let current_term = 1u64;
    let voted_for_option = None;
    let last_log_id = Some(LogId { index: 1, term: 1 });
    let raft_log = Arc::new(create_mock_raft_log(last_log_id));

    // Act
    let state_update = handler
        .handle_vote_request(request, current_term, voted_for_option, &raft_log)
        .await
        .unwrap();

    // Assert
    assert_eq!(
        state_update.term_update,
        Some(2),
        "Term should be updated to 2"
    );
    assert!(
        state_update.new_voted_for.is_some(),
        "Vote should be granted"
    );
    assert_eq!(
        state_update.new_voted_for.unwrap().voted_for_id,
        1,
        "Should vote for candidate 1"
    );
    assert_eq!(
        state_update.new_voted_for.unwrap().voted_for_term,
        2,
        "Vote should be for term 2"
    );
}

/// Test: Voter denies vote when request term is lower than current term
///
/// Scenario:
/// - Current term: 3
/// - Request term: 2 (lower)
/// - Vote should not be granted
///
/// Expected: Vote denied, no state update
#[tokio::test]
async fn test_handle_vote_request_deny_lower_term() {
    // Arrange
    let handler = create_handler(2);
    let request = create_vote_request(2, 1, 5, 2);
    let current_term = 3u64;
    let voted_for_option = None;
    let last_log_id = Some(LogId { index: 5, term: 3 });
    let raft_log = Arc::new(create_mock_raft_log(last_log_id));

    // Act
    let state_update = handler
        .handle_vote_request(request, current_term, voted_for_option, &raft_log)
        .await
        .unwrap();

    // Assert
    assert_eq!(
        state_update.term_update, None,
        "Term should not be updated for lower request term"
    );
    assert_eq!(
        state_update.new_voted_for, None,
        "Vote should not be granted for lower term"
    );
}

/// Test: Voter denies vote when candidate's log is not as recent
///
/// Scenario:
/// - Current term: 1
/// - Request term: 1 (same)
/// - Local log: index=10, term=2 (more recent than candidate)
/// - Candidate log: index=5, term=1 (less recent)
/// - Voted for: None
///
/// Expected: Vote denied because candidate's log is stale
#[tokio::test]
async fn test_handle_vote_request_deny_stale_log() {
    // Arrange
    let handler = create_handler(2);
    let request = create_vote_request(1, 1, 5, 1); // Candidate has older log
    let current_term = 1u64;
    let voted_for_option = None;
    let last_log_id = Some(LogId { index: 10, term: 2 }); // Local log is more recent
    let raft_log = Arc::new(create_mock_raft_log(last_log_id));

    // Act
    let state_update = handler
        .handle_vote_request(request, current_term, voted_for_option, &raft_log)
        .await
        .unwrap();

    // Assert
    assert_eq!(
        state_update.new_voted_for, None,
        "Vote should be denied for stale log"
    );
}

/// Test: Voter denies vote when already voted for a different candidate in same term
///
/// Scenario:
/// - Current term: 2
/// - Request term: 2 (same)
/// - Already voted for: node 1 in term 2
/// - Request from: node 3
/// - Local log: index=3, term=2
/// - Candidate log: index=3, term=2
///
/// Expected: Vote denied (already voted for someone else)
#[tokio::test]
async fn test_handle_vote_request_deny_already_voted_different_candidate() {
    // Arrange
    let handler = create_handler(2);
    let request = create_vote_request(2, 3, 3, 2); // Request from node 3
    let current_term = 2u64;
    let voted_for_option = Some(VotedFor {
        voted_for_id: 1,
        voted_for_term: 2,
        committed: false,
    }); // Already voted for node 1
    let last_log_id = Some(LogId { index: 3, term: 2 });
    let raft_log = Arc::new(create_mock_raft_log(last_log_id));

    // Act
    let state_update = handler
        .handle_vote_request(request, current_term, voted_for_option, &raft_log)
        .await
        .unwrap();

    // Assert
    assert_eq!(
        state_update.new_voted_for, None,
        "Vote should be denied when already voted for different candidate"
    );
}

/// Test: Voter grants vote when re-voting for the same candidate in same term
///
/// Scenario:
/// - Current term: 2
/// - Request term: 2 (same)
/// - Already voted for: node 1 in term 2
/// - Request from: node 1 (same candidate)
/// - Local log: index=3, term=2
/// - Candidate log: index=3, term=2
///
/// Expected: Vote granted (re-voting for same candidate is allowed)
#[tokio::test]
async fn test_handle_vote_request_grant_revote_same_candidate() {
    // Arrange
    let handler = create_handler(2);
    let request = create_vote_request(2, 1, 3, 2); // Request from node 1
    let current_term = 2u64;
    let voted_for_option = Some(VotedFor {
        voted_for_id: 1,
        voted_for_term: 2,
        committed: false,
    }); // Already voted for node 1
    let last_log_id = Some(LogId { index: 3, term: 2 });
    let raft_log = Arc::new(create_mock_raft_log(last_log_id));

    // Act
    let state_update = handler
        .handle_vote_request(request, current_term, voted_for_option, &raft_log)
        .await
        .unwrap();

    // Assert
    assert!(
        state_update.new_voted_for.is_some(),
        "Vote should be granted for re-voting"
    );
    assert_eq!(
        state_update.new_voted_for.unwrap().voted_for_id,
        1,
        "Should vote for the same candidate"
    );
}

/// Test: Voter grants vote when higher term provided (resets voted_for)
///
/// Scenario:
/// - Current term: 2
/// - Request term: 3 (higher)
/// - Already voted for: node 1 in term 2
/// - Request from: node 3
/// - Local log: index=3, term=2
/// - Candidate log: index=4, term=3
///
/// Expected: Vote granted (higher term resets vote)
#[tokio::test]
async fn test_handle_vote_request_grant_higher_term_resets_vote() {
    // Arrange
    let handler = create_handler(2);
    let request = create_vote_request(3, 3, 4, 3); // Higher term
    let current_term = 2u64;
    let voted_for_option = Some(VotedFor {
        voted_for_id: 1,
        voted_for_term: 2,
        committed: false,
    }); // Voted for node 1 in term 2
    let last_log_id = Some(LogId { index: 3, term: 2 });
    let raft_log = Arc::new(create_mock_raft_log(last_log_id));

    // Act
    let state_update = handler
        .handle_vote_request(request, current_term, voted_for_option, &raft_log)
        .await
        .unwrap();

    // Assert
    assert_eq!(
        state_update.term_update,
        Some(3),
        "Term should be updated to 3"
    );
    assert!(
        state_update.new_voted_for.is_some(),
        "Vote should be granted for higher term"
    );
    assert_eq!(
        state_update.new_voted_for.unwrap().voted_for_id,
        3,
        "Should vote for node 3"
    );
}

/// Test: Voter grants vote when candidate has higher log term
///
/// Scenario:
/// - Current term: 1
/// - Request term: 1 (same)
/// - Local log: index=10, term=1
/// - Candidate log: index=5, term=2 (higher term, less index but more recent)
///
/// Expected: Vote granted (term takes precedence)
#[tokio::test]
async fn test_handle_vote_request_grant_higher_log_term() {
    // Arrange
    let handler = create_handler(2);
    let request = create_vote_request(1, 1, 5, 2); // Higher log term
    let current_term = 1u64;
    let voted_for_option = None;
    let last_log_id = Some(LogId { index: 10, term: 1 });
    let raft_log = Arc::new(create_mock_raft_log(last_log_id));

    // Act
    let state_update = handler
        .handle_vote_request(request, current_term, voted_for_option, &raft_log)
        .await
        .unwrap();

    // Assert
    assert!(
        state_update.new_voted_for.is_some(),
        "Vote should be granted for higher log term"
    );
}

/// Test: Voter grants vote when same log term but higher index
///
/// Scenario:
/// - Current term: 1
/// - Request term: 1 (same)
/// - Local log: index=5, term=2
/// - Candidate log: index=10, term=2 (same term, higher index)
///
/// Expected: Vote granted (higher index is more recent)
#[tokio::test]
async fn test_handle_vote_request_grant_higher_index_same_term() {
    // Arrange
    let handler = create_handler(2);
    let request = create_vote_request(1, 1, 10, 2); // Same term, higher index
    let current_term = 1u64;
    let voted_for_option = None;
    let last_log_id = Some(LogId { index: 5, term: 2 });
    let raft_log = Arc::new(create_mock_raft_log(last_log_id));

    // Act
    let state_update = handler
        .handle_vote_request(request, current_term, voted_for_option, &raft_log)
        .await
        .unwrap();

    // Assert
    assert!(
        state_update.new_voted_for.is_some(),
        "Vote should be granted for higher index in same term"
    );
}

/// Test: Empty log (no entries) votes for valid candidate
///
/// Scenario:
/// - Local node has no log entries (None)
/// - Candidate has index=1, term=1
/// - Request with valid term
///
/// Expected: Vote granted
#[tokio::test]
async fn test_handle_vote_request_empty_local_log() {
    // Arrange
    let handler = create_handler(2);
    let request = create_vote_request(1, 1, 1, 1);
    let current_term = 0u64;
    let voted_for_option = None;
    let last_log_id = None;
    let raft_log = Arc::new(create_mock_raft_log(last_log_id));

    // Act
    let state_update = handler
        .handle_vote_request(request, current_term, voted_for_option, &raft_log)
        .await
        .unwrap();

    // Assert
    assert!(
        state_update.new_voted_for.is_some(),
        "Vote should be granted for candidate with valid log when local log is empty"
    );
}

/// Test: Candidate with empty log votes for someone with entries
///
/// Scenario:
/// - Local node has no entries (None)
/// - Requesting vote from candidate (also empty)
/// - Request has index=0, term=0
///
/// Expected: Vote granted (both have same recency)
#[tokio::test]
async fn test_handle_vote_request_both_empty_logs() {
    // Arrange
    let handler = create_handler(2);
    let request = create_vote_request(1, 1, 0, 0);
    let current_term = 0u64;
    let voted_for_option = None;
    let last_log_id = None;
    let raft_log = Arc::new(create_mock_raft_log(last_log_id));

    // Act
    let state_update = handler
        .handle_vote_request(request, current_term, voted_for_option, &raft_log)
        .await
        .unwrap();

    // Assert
    assert!(
        state_update.new_voted_for.is_some(),
        "Vote should be granted when both have empty logs"
    );
}

// ============================================================================
// test_check_vote_request_is_legal_* - Legal Check
// ============================================================================

/// Test: Check vote request legality - lower term is rejected
#[tokio::test]
async fn test_check_vote_request_is_legal_lower_term() {
    // Arrange
    let handler = create_handler(2);
    let request = create_vote_request(1, 1, 5, 2);
    let current_term = 2u64;
    let last_log_index = 5u64;
    let last_log_term = 2u64;
    let voted_for_option = None;

    // Act
    let is_legal = handler.check_vote_request_is_legal(
        &request,
        current_term,
        last_log_index,
        last_log_term,
        voted_for_option,
    );

    // Assert
    assert!(!is_legal, "Request with lower term should be rejected");
}

/// Test: Check vote request legality - stale log is rejected
#[tokio::test]
async fn test_check_vote_request_is_legal_stale_log() {
    // Arrange
    let handler = create_handler(2);
    let request = create_vote_request(2, 1, 3, 1); // Lower log term
    let current_term = 2u64;
    let last_log_index = 5u64;
    let last_log_term = 2u64; // Local log is more recent
    let voted_for_option = None;

    // Act
    let is_legal = handler.check_vote_request_is_legal(
        &request,
        current_term,
        last_log_index,
        last_log_term,
        voted_for_option,
    );

    // Assert
    assert!(!is_legal, "Request with stale log should be rejected");
}

/// Test: Check vote request legality - already voted for different candidate
#[tokio::test]
async fn test_check_vote_request_is_legal_already_voted_different() {
    // Arrange
    let handler = create_handler(2);
    let request = create_vote_request(2, 3, 5, 2); // Request from node 3
    let current_term = 2u64;
    let last_log_index = 5u64;
    let last_log_term = 2u64;
    let voted_for_option = Some(VotedFor {
        voted_for_id: 1,
        voted_for_term: 2,
        committed: false,
    }); // Already voted for node 1

    // Act
    let is_legal = handler.check_vote_request_is_legal(
        &request,
        current_term,
        last_log_index,
        last_log_term,
        voted_for_option,
    );

    // Assert
    assert!(
        !is_legal,
        "Request should be rejected when already voted for different candidate"
    );
}

/// Test: Check vote request legality - valid request is accepted
#[tokio::test]
async fn test_check_vote_request_is_legal_valid_request() {
    // Arrange
    let handler = create_handler(2);
    let request = create_vote_request(2, 1, 5, 2); // Valid request
    let current_term = 2u64;
    let last_log_index = 5u64;
    let last_log_term = 2u64;
    let voted_for_option = None;

    // Act
    let is_legal = handler.check_vote_request_is_legal(
        &request,
        current_term,
        last_log_index,
        last_log_term,
        voted_for_option,
    );

    // Assert
    assert!(is_legal, "Valid request should be accepted");
}

// ============================================================================
// Edge Cases and Protocol Compliance
// ============================================================================

/// Test: Voter handles term 0 (initialization state)
///
/// Scenario: Testing behavior with uninitialized term=0
#[tokio::test]
async fn test_handle_vote_request_term_zero() {
    // Arrange
    let handler = create_handler(2);
    let request = create_vote_request(0, 1, 0, 0);
    let current_term = 0u64;
    let voted_for_option = None;
    let last_log_id = None;
    let raft_log = Arc::new(create_mock_raft_log(last_log_id));

    // Act
    let state_update = handler
        .handle_vote_request(request, current_term, voted_for_option, &raft_log)
        .await
        .unwrap();

    // Assert - should handle gracefully without panic
    assert_eq!(state_update.term_update, None);
}

/// Test: Very large term numbers (overflow check)
///
/// Scenario: Testing with u64::MAX term values
#[tokio::test]
async fn test_handle_vote_request_large_term_numbers() {
    // Arrange
    let handler = create_handler(2);
    let large_term = u64::MAX;
    let request = create_vote_request(large_term, 1, 100, large_term);
    let current_term = large_term - 1;
    let voted_for_option = None;
    let last_log_id = Some(LogId {
        index: 100,
        term: large_term,
    });
    let raft_log = Arc::new(create_mock_raft_log(last_log_id));

    // Act
    let state_update = handler
        .handle_vote_request(request, current_term, voted_for_option, &raft_log)
        .await
        .unwrap();

    // Assert
    assert_eq!(state_update.term_update, Some(large_term));
}

// ================================================================================================
// Tests for Single-Node Cluster Support (Issue #179)
// ================================================================================================

#[cfg(test)]
mod single_node_election_tests {
    use std::collections::HashSet;

    use d_engine_proto::server::cluster::NodeMeta;
    use d_engine_proto::server::election::VoteResponse;

    use super::*;
    use crate::ConsensusError;
    use crate::ElectionError;
    use crate::Error;
    use crate::MockMembership;
    use crate::MockTransport;
    use crate::RaftNodeConfig;
    use crate::VoteResult;

    #[tokio::test]
    async fn test_single_node_auto_wins_election() {
        // Arrange
        let handler = ElectionHandler::<MockTypeConfig>::new(1);
        let mut mock_membership = MockMembership::new();

        // Mock: is_single_node_cluster() returns true for single-node
        mock_membership.expect_is_single_node_cluster().times(1).returning(|| true);

        // voters() should NOT be called (early return before this check)
        mock_membership.expect_voters().times(0);

        let membership = Arc::new(mock_membership);
        let raft_log = Arc::new(create_mock_raft_log(None));
        let mock_transport = MockTransport::new();
        let transport = Arc::new(mock_transport);
        let settings = Arc::new(RaftNodeConfig::default());

        // Act
        let result = handler
            .broadcast_vote_requests(1, membership, &raft_log, &transport, &settings)
            .await;

        // Assert
        assert!(
            result.is_ok(),
            "Single-node should automatically win election"
        );
    }

    #[tokio::test]
    async fn test_three_node_cluster_goes_through_normal_election() {
        // Arrange
        let handler = ElectionHandler::<MockTypeConfig>::new(1);
        let mut mock_membership = MockMembership::new();

        // Mock: is_single_node_cluster() returns false for multi-node
        mock_membership.expect_is_single_node_cluster().times(1).returning(|| false);

        // Mock: voters() returns 2 peers
        mock_membership.expect_voters().times(1).returning(|| {
            vec![
                NodeMeta {
                    id: 2,
                    address: "127.0.0.1:9082".to_string(),
                    role: 0,
                    status: 2,
                },
                NodeMeta {
                    id: 3,
                    address: "127.0.0.1:9083".to_string(),
                    role: 0,
                    status: 2,
                },
            ]
        });

        let membership = Arc::new(mock_membership);
        let raft_log = Arc::new(create_mock_raft_log(None));

        let mut mock_transport = MockTransport::new();
        // Mock transport to return majority votes
        mock_transport.expect_send_vote_requests().times(1).returning(
            |_req, _retry, _membership| {
                Ok(VoteResult {
                    peer_ids: HashSet::from([2, 3]),
                    responses: vec![
                        Ok(VoteResponse {
                            term: 1,
                            vote_granted: true,
                            last_log_index: 0,
                            last_log_term: 0,
                        }),
                        Ok(VoteResponse {
                            term: 1,
                            vote_granted: true,
                            last_log_index: 0,
                            last_log_term: 0,
                        }),
                    ],
                })
            },
        );

        let transport = Arc::new(mock_transport);
        let settings = Arc::new(RaftNodeConfig::default());

        // Act
        let result = handler
            .broadcast_vote_requests(1, membership, &raft_log, &transport, &settings)
            .await;

        // Assert
        assert!(
            result.is_ok(),
            "Three-node cluster should complete normal election"
        );
    }

    #[tokio::test]
    async fn test_network_partition_with_empty_voters_still_reports_error() {
        // Arrange
        let handler = ElectionHandler::<MockTypeConfig>::new(1);
        let mut mock_membership = MockMembership::new();

        // Mock: is_single_node_cluster() returns false for multi-node (network partition scenario)
        mock_membership.expect_is_single_node_cluster().times(1).returning(|| false);

        // Mock: voters() returns empty (network partition)
        mock_membership.expect_voters().times(1).returning(Vec::new);

        let membership = Arc::new(mock_membership);
        let raft_log = Arc::new(create_mock_raft_log(None));
        let mock_transport = MockTransport::new();
        let transport = Arc::new(mock_transport);
        let settings = Arc::new(RaftNodeConfig::default());

        // Act
        let result = handler
            .broadcast_vote_requests(1, membership, &raft_log, &transport, &settings)
            .await;

        // Assert
        assert!(result.is_err(), "Network partition should return error");
        assert!(
            matches!(
                result.unwrap_err(),
                Error::Consensus(crate::ConsensusError::Election(
                    ElectionError::NoVotingMemberFound { .. }
                ))
            ),
            "Should return NoVotingMemberFound error"
        );
    }

    // ============================================================================
    // test_broadcast_vote_requests_* - Vote Broadcasting Tests
    // ============================================================================

    /// Test: broadcast_vote_requests returns error when cluster has no voting members
    ///
    /// Scenario:
    /// - Multi-node cluster configuration (not single-node)
    /// - Membership returns empty voters list
    /// - Attempt to broadcast vote requests for election
    ///
    /// Expected:
    /// - Returns ElectionError::NoVotingMemberFound
    /// - No RPC calls are made (raft_log and transport expectations: times(0))
    ///
    /// This validates the early validation check that prevents unnecessary
    /// network operations when there are no peers to vote.
    #[tokio::test]
    async fn test_broadcast_vote_requests_returns_error_when_no_voting_members() {
        // Arrange
        let election_handler = ElectionHandler::<MockTypeConfig>::new(1);
        let term = 1;

        // Mock raft_log - expect NO calls since we fail validation before accessing log
        let mut raft_log_mock = MockRaftLog::new();
        raft_log_mock
            .expect_last_log_id()
            .times(0)
            .returning(|| Some(LogId { index: 1, term: 1 }));

        // Mock transport - expect NO calls since we fail validation before sending RPCs
        let mut transport_mock = MockTransport::new();
        transport_mock.expect_send_vote_requests().times(0).returning(|_, _, _| {
            Ok(VoteResult {
                peer_ids: vec![2].into_iter().collect(),
                responses: vec![Ok(VoteResponse {
                    term: 1,
                    vote_granted: false,
                    last_log_index: 1,
                    last_log_term: 1,
                })],
            })
        });

        // Mock membership with empty voters (core test_utils provides this default)
        let mut membership = MockMembership::new();
        membership.expect_voters().returning(Vec::new);
        membership.expect_is_single_node_cluster().returning(|| false);

        // Create minimal node_config with TempDir (no file system pollution)
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut node_config = RaftNodeConfig::new().expect("Should create default config");
        node_config.cluster.db_root_dir = temp_dir.path().to_path_buf();
        let node_config = node_config.validate().expect("Should validate config");

        // Act
        let result = election_handler
            .broadcast_vote_requests(
                term,
                Arc::new(membership),
                &Arc::new(raft_log_mock),
                &Arc::new(transport_mock),
                &Arc::new(node_config),
            )
            .await;

        // Assert
        assert!(
            result.is_err(),
            "Should return error when no voting members"
        );
        assert!(
            matches!(
                result.unwrap_err(),
                Error::Consensus(ConsensusError::Election(
                    ElectionError::NoVotingMemberFound { candidate_id: 1 }
                ))
            ),
            "Expected NoVotingMemberFound error with candidate_id=1"
        );
    }

    /// Test: broadcast_vote_requests when majority of peers reject vote due to log conflict
    ///
    /// FIXME(migration): This test is a FALSE POSITIVE from the original codebase.
    ///
    /// **Problem**: The test uses `if let` pattern matching without `else` or `assert!`,
    /// causing it to pass silently even when the wrong error type is returned.
    ///
    /// **Current behavior**:
    /// - Uses `mock_membership()` which returns empty voters
    /// - Function returns `NoVotingMemberFound` error immediately
    /// - `if let LogConflict` fails to match, skips assertions, test passes silently
    ///
    /// **Intended behavior**: Should test the scenario where:
    /// - Cluster has voting members
    /// - Peers reject votes because their logs are more up-to-date
    /// - Should return `LogConflict` error
    ///
    /// **Fix required**:
    /// 1. Configure membership with actual voters
    /// 2. Configure transport to return `vote_granted=false` responses
    /// 3. Change `if let` to `assert!(matches!())` for proper validation
    ///
    /// **Original test location**:
    /// `d-engine-server/tests/components/election/election_handler_test.rs::test_broadcast_vote_requests_case2`
    ///
    /// Scenario (intended, not currently tested):
    /// - Cluster has multiple voting members
    /// - Candidate broadcasts vote requests
    /// - Majority of peers reject due to having more recent logs
    ///
    /// Expected (intended):
    /// - Returns ElectionError::LogConflict with conflict details
    #[tokio::test]
    #[ignore = "False positive test - needs fix before enabling (see FIXME above)"]
    async fn test_broadcast_vote_requests_majority_reject_due_to_log_conflict() {
        // Original test setup - preserved for reference
        let election_handler = ElectionHandler::<MockTypeConfig>::new(1);
        let term = 1;

        // Mock raft_log - times(0) because function returns early with NoVotingMemberFound
        let mut raft_log_mock = MockRaftLog::new();
        raft_log_mock
            .expect_last_log_id()
            .times(0)
            .returning(|| Some(LogId { index: 1, term: 1 }));

        // Mock transport - times(0) because function returns early
        let mut transport_mock = MockTransport::new();
        transport_mock.expect_send_vote_requests().times(0).returning(|_, _, _| {
            Ok(VoteResult {
                peer_ids: vec![2].into_iter().collect(),
                responses: vec![Ok(VoteResponse {
                    term: 1,
                    vote_granted: false,
                    last_log_index: 1,
                    last_log_term: 1,
                })],
            })
        });

        // Mock membership with empty voters (causes immediate NoVotingMemberFound error)
        let mut membership = MockMembership::new();
        membership.expect_voters().returning(Vec::new);
        membership.expect_is_single_node_cluster().returning(|| false);

        // Create minimal node_config with TempDir
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut node_config = RaftNodeConfig::new().expect("Should create default config");
        node_config.cluster.db_root_dir = temp_dir.path().to_path_buf();
        let node_config = node_config.validate().expect("Should validate config");

        // Execute - will return NoVotingMemberFound, not LogConflict
        let e = election_handler
            .broadcast_vote_requests(
                term,
                Arc::new(membership),
                &Arc::new(raft_log_mock),
                &Arc::new(transport_mock),
                &Arc::new(node_config),
            )
            .await
            .unwrap_err();

        // Original assertion - NEVER EXECUTES because pattern doesn't match
        // Test passes silently without validating anything
        if let Error::Consensus(ConsensusError::Election(ElectionError::LogConflict {
            index,
            expected_term,
            actual_term,
        })) = e
        {
            assert_eq!(index, 1);
            assert_eq!(actual_term, 1);
            assert_eq!(expected_term, 1);
        }

        // TODO: Replace above with proper test implementation:
        // assert!(
        //     matches!(
        //         e,
        //         Error::Consensus(ConsensusError::Election(
        //             ElectionError::LogConflict { index: 1, expected_term: 1, actual_term: 1 }
        //         ))
        //     ),
        //     "Expected LogConflict error, got: {:?}", e
        // );
    }

    /// Test: broadcast_vote_requests succeeds when receiving majority of positive votes
    ///
    /// Scenario:
    /// - Two-node cluster (candidate + 1 peer)
    /// - Candidate broadcasts vote request with term=1
    /// - Peer responds with vote_granted=true
    /// - Candidate achieves majority (1 self + 1 peer = 2/2)
    ///
    /// Expected:
    /// - Returns Ok(()) indicating election success
    ///
    /// This is the core "winning election" scenario in Raft where a candidate
    /// successfully obtains majority votes and can transition to Leader role.
    ///
    /// Original test location:
    /// `d-engine-server/tests/components/election/election_handler_test.rs::test_broadcast_vote_requests_case3`
    #[tokio::test]
    async fn test_broadcast_vote_requests_wins_election_with_majority_votes() {
        let election_handler = ElectionHandler::<MockTypeConfig>::new(1);
        let term = 1;

        // Mock raft_log - will be called once to get last log info for vote request
        let mut raft_log_mock = MockRaftLog::new();
        raft_log_mock
            .expect_last_log_id()
            .times(1)
            .returning(|| Some(LogId { index: 1, term: 1 }));

        // Mock transport - returns successful vote from peer
        let mut transport_mock = MockTransport::new();
        transport_mock.expect_send_vote_requests().times(1).returning(|_, _, _| {
            Ok(VoteResult {
                peer_ids: vec![2].into_iter().collect(),
                responses: vec![Ok(VoteResponse {
                    term: 1,
                    vote_granted: true,
                    last_log_index: 1,
                    last_log_term: 1,
                })],
            })
        });

        // Mock membership - two-node cluster with one voting peer
        let mut membership = MockMembership::new();
        membership.expect_is_single_node_cluster().returning(|| false);
        membership.expect_initial_cluster_size().returning(|| 2);
        membership.expect_voters().returning(move || {
            use d_engine_proto::common::NodeRole::Follower;
            use d_engine_proto::common::NodeStatus;
            use d_engine_proto::server::cluster::NodeMeta;

            vec![NodeMeta {
                id: 2,
                address: "http://127.0.0.1:55001".to_string(),
                role: Follower.into(),
                status: NodeStatus::Active.into(),
            }]
        });

        // Create minimal node_config with TempDir
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut node_config = RaftNodeConfig::new().expect("Should create default config");
        node_config.cluster.db_root_dir = temp_dir.path().to_path_buf();
        let node_config = node_config.validate().expect("Should validate config");

        // Execute
        let result = election_handler
            .broadcast_vote_requests(
                term,
                Arc::new(membership),
                &Arc::new(raft_log_mock),
                &Arc::new(transport_mock),
                &Arc::new(node_config),
            )
            .await;

        // Verify - should succeed with majority votes
        assert!(
            result.is_ok(),
            "Expected successful election with majority votes, got: {result:?}"
        );
    }

    /// Test: broadcast_vote_requests when peer responds with higher term
    ///
    /// FIXME(migration): This test is a FALSE POSITIVE from the original codebase.
    ///
    /// **Problem**: Uses `if let` without proper assertion, passes silently with wrong error.
    ///
    /// **Current behavior**:
    /// - Uses `mock_membership()` which returns empty voters
    /// - Function returns `NoVotingMemberFound` immediately
    /// - `if let HigherTerm` fails to match, test passes silently
    ///
    /// **Intended behavior**: Should test the scenario where:
    /// - Candidate broadcasts vote requests to peers
    /// - Peer responds with higher term in vote response
    /// - Should return `HigherTerm` error causing candidate to step down
    ///
    /// **Fix required**:
    /// 1. Configure membership with actual voters
    /// 2. Configure transport to return response with higher term
    /// 3. Change `if let` to `assert!(matches!())` for proper validation
    ///
    /// Original test location:
    /// `d-engine-server/tests/components/election/election_handler_test.rs::test_broadcast_vote_requests_case4`
    #[tokio::test]
    #[ignore = "False positive test - needs fix before enabling (see FIXME above)"]
    async fn test_broadcast_vote_requests_peer_has_higher_term() {
        let election_handler = ElectionHandler::<MockTypeConfig>::new(1);
        let my_last_log_term = 3;

        // Mock transport - never called because function returns early
        let transport_mock = MockTransport::new();

        // Mock raft_log - never called
        let raft_log_mock = MockRaftLog::new();

        // Mock membership with empty voters (causes immediate NoVotingMemberFound)
        let mut membership = MockMembership::new();
        membership.expect_voters().returning(Vec::new);
        membership.expect_is_single_node_cluster().returning(|| false);

        // Create minimal node_config with TempDir
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut node_config = RaftNodeConfig::new().expect("Should create default config");
        node_config.cluster.db_root_dir = temp_dir.path().to_path_buf();
        let node_config = node_config.validate().expect("Should validate config");

        // Execute - will return NoVotingMemberFound, not HigherTerm
        let e = election_handler
            .broadcast_vote_requests(
                my_last_log_term,
                Arc::new(membership),
                &Arc::new(raft_log_mock),
                &Arc::new(transport_mock),
                &Arc::new(node_config),
            )
            .await
            .unwrap_err();

        // Original assertion - NEVER EXECUTES because pattern doesn't match
        if let Error::Consensus(ConsensusError::Election(ElectionError::HigherTerm(higher_term))) =
            e
        {
            assert_eq!(higher_term, my_last_log_term + 1);
        }

        // TODO: Replace with proper implementation that tests HigherTerm scenario
    }

    /// Test: broadcast_vote_requests when peer has higher log index (same term)
    ///
    /// FIXME(migration): This test is a FALSE POSITIVE from the original codebase.
    ///
    /// **Problem**: Uses `if let` without proper assertion, passes silently with wrong error.
    ///
    /// **Current behavior**:
    /// - Uses `mock_membership()` which returns empty voters
    /// - Function returns `NoVotingMemberFound` immediately
    /// - `if let LogConflict` fails to match, test passes silently
    ///
    /// **Intended behavior**: Should test the scenario where:
    /// - Candidate and peer have same last_log_term
    /// - Peer has higher last_log_index (more entries in same term)
    /// - Should return `LogConflict` error
    ///
    /// **Fix required**:
    /// 1. Configure membership with actual voters
    /// 2. Configure transport to return response with higher log index
    /// 3. Change `if let` to `assert!(matches!())` for proper validation
    ///
    /// Original test location:
    /// `d-engine-server/tests/components/election/election_handler_test.rs::test_broadcast_vote_requests_case5`
    #[tokio::test]
    #[ignore = "False positive test - needs fix before enabling (see FIXME above)"]
    async fn test_broadcast_vote_requests_peer_has_higher_log_index() {
        let election_handler = ElectionHandler::<MockTypeConfig>::new(1);
        let my_last_log_index = 1;
        let my_last_log_term = 3;

        // Mock transport - never called
        let transport_mock = MockTransport::new();

        // Mock raft_log - never called
        let raft_log_mock = MockRaftLog::new();

        // Mock membership with empty voters (causes immediate NoVotingMemberFound)
        let mut membership = MockMembership::new();
        membership.expect_voters().returning(Vec::new);
        membership.expect_is_single_node_cluster().returning(|| false);

        // Create minimal node_config with TempDir
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut node_config = RaftNodeConfig::new().expect("Should create default config");
        node_config.cluster.db_root_dir = temp_dir.path().to_path_buf();
        let node_config = node_config.validate().expect("Should validate config");

        // Execute - will return NoVotingMemberFound, not LogConflict
        let e = election_handler
            .broadcast_vote_requests(
                my_last_log_term,
                Arc::new(membership),
                &Arc::new(raft_log_mock),
                &Arc::new(transport_mock),
                &Arc::new(node_config),
            )
            .await
            .unwrap_err();

        // Original assertion - NEVER EXECUTES because pattern doesn't match
        if let Error::Consensus(ConsensusError::Election(ElectionError::LogConflict {
            index,
            expected_term,
            actual_term,
        })) = e
        {
            assert_eq!(index, my_last_log_index);
            assert_eq!(expected_term, my_last_log_term);
            assert_eq!(actual_term, my_last_log_term);
        }

        // TODO: Replace with proper implementation that tests LogConflict scenario
    }

    // ============================================================================
    // test_handle_vote_request_* - Processing Incoming Vote Requests
    // ============================================================================

    /// Test: handle_vote_request grants vote for valid higher term request
    ///
    /// Scenario:
    /// - Current node is at term 1
    /// - Receives vote request for term 2 (higher)
    /// - Request has more recent log (index 2 vs local index 1)
    /// - Node has not voted in current term
    ///
    /// Expected:
    /// - Returns state update with:
    ///   - new_voted_for = Some(candidate_id)
    ///   - term_update = Some(2) (advance to new term)
    ///
    /// This validates the core Raft rule: grant vote to first valid request
    /// with higher term and at-least-as-up-to-date log.
    ///
    /// Original test location:
    /// `d-engine-server/tests/components/election/election_handler_test.rs::test_handle_vote_request_case1`
    #[tokio::test]
    async fn test_handle_vote_request_grants_vote_for_valid_higher_term() {
        let election_handler = ElectionHandler::<MockTypeConfig>::new(1);

        // Mock raft_log with local log state
        let mut raft_log_mock = MockRaftLog::new();
        raft_log_mock
            .expect_last_log_id()
            .times(1)
            .returning(|| Some(LogId { index: 1, term: 1 }));

        let current_term = 1;
        let request_term = current_term + 1;

        // Vote request from candidate with higher term and more recent log
        let vote_request = VoteRequest {
            term: request_term,
            candidate_id: 1,
            last_log_index: 2, // More recent than local (1)
            last_log_term: 1,
        };

        let voted_for_option = None; // Haven't voted yet

        // Execute
        let result = election_handler
            .handle_vote_request(
                vote_request,
                current_term,
                voted_for_option,
                &Arc::new(raft_log_mock),
            )
            .await;

        // Verify
        assert!(
            result.is_ok(),
            "Should grant vote for valid higher term request"
        );

        let state_update = result.unwrap();
        assert!(
            state_update.new_voted_for.is_some(),
            "Should update voted_for"
        );
        assert_eq!(
            state_update.term_update,
            Some(request_term),
            "Should advance term to request term"
        );
    }

    /// Test: handle_vote_request rejects vote for lower term request
    ///
    /// Scenario:
    /// - Current node is at term 10
    /// - Receives vote request for term 9 (lower/stale)
    /// - Request has more recent log (doesn't matter)
    ///
    /// Expected:
    /// - Returns state update with:
    ///   - new_voted_for = None (vote not granted)
    ///   - term_update = None (stay at current term)
    ///
    /// This validates the Raft rule: reject requests from lower terms,
    /// preventing stale candidates from disrupting the cluster.
    ///
    /// Original test location:
    /// `d-engine-server/tests/components/election/election_handler_test.rs::test_handle_vote_request_case2`
    #[tokio::test]
    async fn test_handle_vote_request_rejects_vote_for_lower_term() {
        let election_handler = ElectionHandler::<MockTypeConfig>::new(1);

        // Mock raft_log
        let mut raft_log_mock = MockRaftLog::new();
        raft_log_mock
            .expect_last_log_id()
            .times(1)
            .returning(|| Some(LogId { index: 1, term: 1 }));

        let current_term = 10;
        let request_term = current_term - 1; // Stale term

        // Vote request with lower term (should be rejected regardless of log)
        let vote_request = VoteRequest {
            term: request_term,
            candidate_id: 1,
            last_log_index: 2,
            last_log_term: 1,
        };

        let voted_for_option = None;

        // Execute
        let result = election_handler
            .handle_vote_request(
                vote_request,
                current_term,
                voted_for_option,
                &Arc::new(raft_log_mock),
            )
            .await;

        // Verify
        assert!(result.is_ok(), "Should not error on stale request");

        let state_update = result.unwrap();
        assert!(
            state_update.new_voted_for.is_none(),
            "Should NOT grant vote for lower term"
        );
        assert_eq!(
            state_update.term_update, None,
            "Should NOT update term for stale request"
        );
    }

    // ============================================================================
    // test_check_vote_request_is_legal_* - Vote Request Legality Validation
    // ============================================================================

    /// Test: check_vote_request_is_legal rejects when current term >= request term
    ///
    /// TODO(migration): This test uses `setup_raft_components()` unnecessarily.
    /// The `check_vote_request_is_legal()` method is a pure function that only needs
    /// an ElectionHandler instance. No file system or network components are needed.
    ///
    /// **Simplification needed**:
    /// Replace `setup_raft_components()` with simple `ElectionHandler::new(1)`
    ///
    /// Scenario:
    /// - Current term is 1 or 2
    /// - Vote request is for term 1
    /// - Local log: index=1, term=1
    /// - Already voted for candidate 1 in term 1
    ///
    /// Expected:
    /// - Returns false (reject vote)
    /// - Reason: Current term is not less than request term
    ///
    /// Original test location:
    /// `d-engine-server/tests/components/election/election_handler_test.rs::test_check_vote_request_is_legal_case_1_1`
    #[tokio::test]
    async fn test_check_vote_request_is_legal_rejects_when_current_term_not_lower() {
        // TODO: Simplify to just `let election_handler = ElectionHandler::<MockTypeConfig>::new(1);`
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut node_config = RaftNodeConfig::new().expect("Should create default config");
        node_config.cluster.db_root_dir = temp_dir.path().to_path_buf();
        let _node_config = node_config.validate().expect("Should validate config");
        let election_handler = ElectionHandler::<MockTypeConfig>::new(1);

        let vote_request = VoteRequest {
            term: 1,
            candidate_id: 1,
            last_log_index: 1,
            last_log_term: 1,
        };
        let last_log_index = 1;
        let last_log_term = 1;
        let voted_for_id = 1;
        let voted_for_term = 1;

        // Test 1: current_term = request_term (equal)
        let current_term = 1;
        assert!(
            !election_handler.check_vote_request_is_legal(
                &vote_request,
                current_term,
                last_log_index,
                last_log_term,
                Some(VotedFor {
                    voted_for_id,
                    voted_for_term,
                    committed: false
                })
            ),
            "Should reject when current_term equals request term"
        );

        // Test 2: current_term > request_term
        let current_term = 2;
        assert!(
            !election_handler.check_vote_request_is_legal(
                &vote_request,
                current_term,
                last_log_index,
                last_log_term,
                Some(VotedFor {
                    voted_for_id,
                    voted_for_term,
                    committed: false
                })
            ),
            "Should reject when current_term is higher than request term"
        );
    }

    /// Test: check_vote_request_is_legal rejects when request log term is not higher
    ///
    /// TODO(migration): Uses `setup_raft_components()` unnecessarily - can be simplified.
    ///
    /// Scenario:
    /// - Current term = 1, request term = 1
    /// - Request log: index=1, term=1
    /// - Local log: index=1, term=2 (higher) OR term=1 (equal)
    /// - Already voted for candidate 1 in term 1
    ///
    /// Expected:
    /// - Returns false (reject vote)
    /// - Reason: Request log term is not more recent than local
    ///
    /// Original test location:
    /// `d-engine-server/tests/components/election/election_handler_test.rs::test_check_vote_request_is_legal_case_1_2`
    #[tokio::test]
    async fn test_check_vote_request_is_legal_rejects_when_request_log_not_more_recent() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut node_config = RaftNodeConfig::new().expect("Should create default config");
        node_config.cluster.db_root_dir = temp_dir.path().to_path_buf();
        let _node_config = node_config.validate().expect("Should validate config");
        let election_handler = ElectionHandler::<MockTypeConfig>::new(1);

        let current_term = 1;
        let vote_request = VoteRequest {
            term: current_term,
            candidate_id: 1,
            last_log_index: 1,
            last_log_term: 1,
        };
        let last_log_index = 1;
        let voted_for_id = 1;
        let voted_for_term = 1;

        // Test 1: Local log term is higher (2 > 1)
        let last_log_term = 2;
        assert!(
            !election_handler.check_vote_request_is_legal(
                &vote_request,
                current_term,
                last_log_index,
                last_log_term,
                Some(VotedFor {
                    voted_for_id,
                    voted_for_term,
                    committed: false
                })
            ),
            "Should reject when local log term is higher"
        );

        // Test 2: Log terms are equal (1 = 1)
        let last_log_term = 1;
        assert!(
            !election_handler.check_vote_request_is_legal(
                &vote_request,
                current_term,
                last_log_index,
                last_log_term,
                Some(VotedFor {
                    voted_for_id,
                    voted_for_term,
                    committed: false
                })
            ),
            "Should reject when log terms are equal but already voted"
        );
    }

    /// Test: check_vote_request_is_legal accepts when request log is more recent
    ///
    /// TODO(migration): Uses `setup_raft_components()` unnecessarily - can be simplified.
    ///
    /// Scenario:
    /// - Current term = 1, request term = 1
    /// - Request log: index=2, term=1 (more entries)
    /// - Local log: index=1, term=1
    /// - Have not voted yet (voted_for = None)
    ///
    /// Expected:
    /// - Returns true (grant vote)
    /// - Reason: Request has same term but higher index (more up-to-date)
    ///
    /// Original test location:
    /// `d-engine-server/tests/components/election/election_handler_test.rs::test_check_vote_request_is_legal_case_1_3`
    #[tokio::test]
    async fn test_check_vote_request_is_legal_accepts_when_request_log_more_recent() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut node_config = RaftNodeConfig::new().expect("Should create default config");
        node_config.cluster.db_root_dir = temp_dir.path().to_path_buf();
        let _node_config = node_config.validate().expect("Should validate config");
        let election_handler = ElectionHandler::<MockTypeConfig>::new(1);

        let current_term = 1;
        let last_log_index = 1;
        let last_log_term = 1;

        let vote_request = VoteRequest {
            term: current_term,
            candidate_id: 1,
            last_log_index: last_log_index + 1, // Higher index
            last_log_term,
        };

        assert!(
            election_handler.check_vote_request_is_legal(
                &vote_request,
                current_term,
                last_log_index,
                last_log_term,
                None, // Haven't voted yet
            ),
            "Should accept when request has higher log index (same term)"
        );
    }

    /// Test: check_vote_request_is_legal rejects when request log index is lower
    ///
    /// TODO(migration): Uses `setup_raft_components()` unnecessarily - can be simplified.
    ///
    /// Scenario:
    /// - Current term = 1, request term = 1
    /// - Request log: index=1, term=1
    /// - Local log: index=2, term=1 (more entries)
    /// - Already voted for candidate 1 in term 1
    ///
    /// Expected:
    /// - Returns false (reject vote)
    /// - Reason: Local log has more entries (higher index) in same term
    ///
    /// Original test location:
    /// `d-engine-server/tests/components/election/election_handler_test.rs::test_check_vote_request_is_legal_case_1_4`
    #[tokio::test]
    async fn test_check_vote_request_is_legal_rejects_when_local_log_more_recent() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut node_config = RaftNodeConfig::new().expect("Should create default config");
        node_config.cluster.db_root_dir = temp_dir.path().to_path_buf();
        let _node_config = node_config.validate().expect("Should validate config");
        let election_handler = ElectionHandler::<MockTypeConfig>::new(1);

        let current_term = 1;
        let vote_request = VoteRequest {
            term: current_term,
            candidate_id: 1,
            last_log_index: 1,
            last_log_term: 1,
        };
        let last_log_index = 2; // Local has more entries
        let last_log_term = 1;
        let voted_for_id = 1;
        let voted_for_term = 1;

        assert!(
            !election_handler.check_vote_request_is_legal(
                &vote_request,
                current_term,
                last_log_index,
                last_log_term,
                Some(VotedFor {
                    voted_for_id,
                    voted_for_term,
                    committed: false
                })
            ),
            "Should reject when local log is more up-to-date"
        );
    }

    /// Test: check_vote_request_is_legal rejects when already voted for different candidate
    ///
    /// TODO(migration): Uses `setup_raft_components()` unnecessarily - can be simplified.
    ///
    /// Scenario:
    /// - Current term = 1, request term = 1
    /// - Request from candidate 1, log: index=3, term=1
    /// - Local log: index=2, term=1 (request is more recent)
    /// - Already voted for candidate 3 (different) in term 1
    ///
    /// Expected:
    /// - Returns false (reject vote)
    /// - Reason: Already granted vote to a different candidate in this term
    ///
    /// This validates the Raft rule: at most one vote per term.
    ///
    /// Original test location:
    /// `d-engine-server/tests/components/election/election_handler_test.rs::test_check_vote_request_is_legal_case_2_1`
    #[tokio::test]
    async fn test_check_vote_request_is_legal_rejects_when_already_voted_for_different_candidate() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut node_config = RaftNodeConfig::new().expect("Should create default config");
        node_config.cluster.db_root_dir = temp_dir.path().to_path_buf();
        let _node_config = node_config.validate().expect("Should validate config");
        let election_handler = ElectionHandler::<MockTypeConfig>::new(1);

        let current_term = 1;
        let vote_request = VoteRequest {
            term: current_term,
            candidate_id: 1,
            last_log_index: 3,
            last_log_term: 1,
        };
        let last_log_index = 2;
        let last_log_term = 1;

        let voted_for_id = 3; // Already voted for different candidate
        let voted_for_term = 1;

        assert!(
            !election_handler.check_vote_request_is_legal(
                &vote_request,
                current_term,
                last_log_index,
                last_log_term,
                Some(VotedFor {
                    voted_for_id,
                    voted_for_term,
                    committed: false
                })
            ),
            "Should reject when already voted for different candidate in same term"
        );
    }

    /// Test: check_vote_request_is_legal rejects when voted in higher term
    ///
    /// TODO(migration): Uses `setup_raft_components()` unnecessarily - can be simplified.
    ///
    /// Scenario:
    /// - Current term = 1, request term = 1
    /// - Request from candidate 1, log: index=3, term=1
    /// - Local log: index=2, term=1
    /// - Previously voted for candidate 1 in term 10 (higher term)
    ///
    /// Expected:
    /// - Returns false (reject vote)
    /// - Reason: Already voted in a higher term (should not happen in normal operation)
    ///
    /// Original test location:
    /// `d-engine-server/tests/components/election/election_handler_test.rs::test_check_vote_request_is_legal_case_2_2`
    #[tokio::test]
    async fn test_check_vote_request_is_legal_rejects_when_voted_in_higher_term() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut node_config = RaftNodeConfig::new().expect("Should create default config");
        node_config.cluster.db_root_dir = temp_dir.path().to_path_buf();
        let _node_config = node_config.validate().expect("Should validate config");
        let election_handler = ElectionHandler::<MockTypeConfig>::new(1);

        let current_term = 1;
        let vote_request = VoteRequest {
            term: current_term,
            candidate_id: 1,
            last_log_index: 3,
            last_log_term: 1,
        };
        let last_log_index = 2;
        let last_log_term = 1;

        let voted_for_id = 1;
        let voted_for_term = 10; // Voted in higher term

        assert!(
            !election_handler.check_vote_request_is_legal(
                &vote_request,
                current_term,
                last_log_index,
                last_log_term,
                Some(VotedFor {
                    voted_for_id,
                    voted_for_term,
                    committed: false
                })
            ),
            "Should reject when already voted in higher term"
        );
    }

    /// Test: check_vote_request_is_legal accepts when re-voting for same candidate
    ///
    /// TODO(migration): Uses `setup_raft_components()` unnecessarily - can be simplified.
    ///
    /// Scenario:
    /// - Current term = 10, request term = 10
    /// - Request from candidate 1, log: index=3, term=1
    /// - Local log: index=2, term=1 (request is more recent)
    /// - Previously voted for candidate 1 in term 1 (lower term)
    ///
    /// Expected:
    /// - Returns true (grant vote)
    /// - Reason: Can vote again for same candidate in new term with more recent log
    ///
    /// This validates idempotent vote granting: same candidate can receive vote
    /// again in a new term.
    ///
    /// Original test location:
    /// `d-engine-server/tests/components/election/election_handler_test.rs::test_check_vote_request_is_legal_case_2_3`
    #[tokio::test]
    async fn test_check_vote_request_is_legal_accepts_revote_for_same_candidate_new_term() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut node_config = RaftNodeConfig::new().expect("Should create default config");
        node_config.cluster.db_root_dir = temp_dir.path().to_path_buf();
        let _node_config = node_config.validate().expect("Should validate config");
        let election_handler = ElectionHandler::<MockTypeConfig>::new(1);

        let current_term = 10; // New term
        let vote_request = VoteRequest {
            term: current_term,
            candidate_id: 1,
            last_log_index: 3,
            last_log_term: 1,
        };
        let last_log_index = 2;
        let last_log_term = 1;

        let voted_for_id = 1; // Same candidate
        let voted_for_term = 1; // But in older term

        assert!(
            election_handler.check_vote_request_is_legal(
                &vote_request,
                current_term,
                last_log_index,
                last_log_term,
                Some(VotedFor {
                    voted_for_id,
                    voted_for_term,
                    committed: false
                })
            ),
            "Should accept re-vote for same candidate in new term"
        );
    }
}