logisheets_controller 1.8.0

the core of LogiSheets
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
1707
1708
1709
1710
1711
1712
1713
1714
use crate::edit_action::{
    AddComment, AuthorInput, CellInput, CommentMention, CreateBlock, CreateChart,
    CreateChartSeries, DeleteCellImage, DeleteChart, DeleteComment, EditComment, EditPayload,
    LineStyleUpdate, ModifyPolicy, MoveChart, PayloadsAction, ResolveComment, SetCellImage,
    SheetRename, StyleUpdateType, UpdateChart, WorkbookUpdateType,
};

#[test]
fn cross_sheet_range_unparses_after_calc() {
    // Regression: a cross-sheet range argument (`Sheet2!A5:B20`) must survive
    // unparse. It used to resolve the range's cells against the formula's own
    // sheet, fail, and render as the literal "error".
    let buf = std::fs::read("../../tests/graph.xlsx").unwrap();
    let mut wb = Workbook::from_file(&buf, "graph".to_string()).unwrap();
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::CellInput(CellInput {
            sheet_idx: 0,
            row: 0,
            col: 25,
            content: "=VLOOKUP(O8,Sheet2!A5:B20,2,FALSE)".to_string(),
        })],
        undoable: true,
        init: false,
    }));
    let ws = wb.get_sheet_by_idx(0).unwrap();
    let f = ws.get_formula(0, 25).unwrap();
    assert!(
        f.contains("Sheet2!A5:B20"),
        "cross-sheet range not preserved: {}",
        f
    );
    assert!(!f.contains("error"), "unparse produced 'error': {}", f);
}

#[test]
fn update_chart_changes_type_and_title() {
    let buf = std::fs::read("../../tests/graph.xlsx").unwrap();
    let mut wb = Workbook::from_file(&buf, "graph".to_string()).unwrap();
    let chart_id = {
        let ws = wb.get_sheet_by_idx(0).unwrap();
        let c = ws.get_charts();
        assert_eq!(c[0].chart_type, "col");
        c[0].chart_id.clone()
    };

    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::UpdateChart(UpdateChart {
            sheet_idx: 0,
            chart_id: chart_id.clone(),
            chart_type: Some("line".to_string()),
            title: Some("My Title".to_string()),
        })],
        undoable: true,
        init: false,
    }));

    let ws = wb.get_sheet_by_idx(0).unwrap();
    let charts = ws.get_charts();
    let c = &charts[0];
    assert_eq!(c.chart_type, "line", "type changed");
    assert_eq!(c.title.as_deref(), Some("My Title"), "title set");
    // Data references are preserved through the regeneration.
    assert_eq!(c.series.len(), 3);
    assert_eq!(
        c.series[0].values,
        vec![Some(11.0), Some(13.0), Some(15.0), Some(24.0)],
        "series data preserved"
    );
}

#[test]
fn create_chart_from_scratch() {
    // Start from an empty workbook; put some numbers in B1:C2 to reference.
    let mut wb = Workbook::default();
    let inputs = [
        (0usize, 1usize, "10"),
        (0, 2, "20"),
        (1, 1, "30"),
        (1, 2, "40"),
    ];
    let payloads: Vec<EditPayload> = inputs
        .iter()
        .map(|(r, c, v)| {
            EditPayload::CellInput(CellInput {
                sheet_idx: 0,
                row: *r,
                col: *c,
                content: v.to_string(),
            })
        })
        .collect();
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads,
        undoable: true,
        init: false,
    }));

    // Create a column chart with two series referencing those cells.
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::CreateChart(CreateChart {
            sheet_idx: 0,
            chart_id: "chartNew".to_string(),
            chart_type: "col".to_string(),
            from_row: 4,
            from_col: 1,
            from_col_off: 0,
            from_row_off: 0,
            to_row: 18,
            to_col: 8,
            to_col_off: 0,
            to_row_off: 0,
            title: Some("My Chart".to_string()),
            categories_ref: None,
            series: vec![
                CreateChartSeries {
                    name: Some("Row1".to_string()),
                    value_ref: "Sheet1!$B$1:$C$1".to_string(),
                },
                CreateChartSeries {
                    name: Some("Row2".to_string()),
                    value_ref: "Sheet1!$B$2:$C$2".to_string(),
                },
            ],
        })],
        undoable: true,
        init: false,
    }));

    // The new chart is visible via the display API with live values.
    let ws = wb.get_sheet_by_idx(0).unwrap();
    let charts = ws.get_charts();
    assert_eq!(charts.len(), 1, "chart created");
    let c = &charts[0];
    assert_eq!(c.chart_type, "col");
    assert_eq!(c.title.as_deref(), Some("My Chart"));
    assert_eq!(c.series.len(), 2);
    assert_eq!(c.series[0].values, vec![Some(10.0), Some(20.0)]);
    assert_eq!(c.series[1].values, vec![Some(30.0), Some(40.0)]);
    assert_eq!((c.from_row, c.from_col), (4, 1));
    drop(ws);

    // It survives save/reload.
    let bytes = wb.save().unwrap();
    let wb2 = Workbook::from_file(&bytes, "reloaded".to_string()).unwrap();
    let ws2 = wb2.get_sheet_by_idx(0).unwrap();
    let charts2 = ws2.get_charts();
    assert_eq!(charts2.len(), 1, "created chart persists");
    assert_eq!(charts2[0].series[0].values, vec![Some(10.0), Some(20.0)]);
}

#[test]
fn delete_chart_removes_it() {
    let buf = std::fs::read("../../tests/graph.xlsx").unwrap();
    let mut wb = Workbook::from_file(&buf, "graph".to_string()).unwrap();
    let chart_id = {
        let ws = wb.get_sheet_by_idx(0).unwrap();
        ws.get_charts().first().expect("chart present").chart_id.clone()
    };

    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::DeleteChart(DeleteChart {
            sheet_idx: 0,
            chart_id,
        })],
        undoable: true,
        init: false,
    }));

    let ws = wb.get_sheet_by_idx(0).unwrap();
    assert!(ws.get_charts().is_empty(), "chart should be deleted");
    drop(ws);

    // Deletion persists through save/reload.
    let bytes = wb.save().unwrap();
    let wb2 = Workbook::from_file(&bytes, "reloaded".to_string()).unwrap();
    assert!(
        wb2.get_sheet_by_idx(0).unwrap().get_charts().is_empty(),
        "deletion should persist"
    );
}

use super::{EditAction, Workbook};

#[test]
fn chart_reflects_live_data() {
    let buf = std::fs::read("../../tests/graph.xlsx").unwrap();
    let mut wb = Workbook::from_file(&buf, "graph".to_string()).unwrap();

    // series[0] references Sheet1!$B$2:$E$2 → [11, 13, 15, 24] initially.
    {
        let ws = wb.get_sheet_by_idx(0).unwrap();
        let charts = ws.get_charts();
        assert_eq!(
            charts[0].series[0].values,
            vec![Some(11.0), Some(13.0), Some(15.0), Some(24.0)],
            "initial live values match the source range"
        );
    }

    // Edit B2 (row 1, col 1) → 100. The chart should reflect it (values are
    // read live from the source range, not the OOXML cache).
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::CellInput(CellInput {
            sheet_idx: 0,
            row: 1,
            col: 1,
            content: "100".to_string(),
        })],
        undoable: true,
        init: false,
    }));

    let ws = wb.get_sheet_by_idx(0).unwrap();
    let charts = ws.get_charts();
    assert_eq!(
        charts[0].series[0].values[0],
        Some(100.0),
        "chart should reflect the edited cell"
    );
    assert_eq!(charts[0].series[0].values[1], Some(13.0), "others unchanged");

    // Series scheme colors (accent1..3) resolve to theme RGB hex.
    let color = charts[0].series[0].color.clone();
    assert!(
        color.as_ref().is_some_and(|c| c.len() == 6 || c.len() == 8),
        "series color should resolve to a theme hex, got {:?}",
        color
    );
}

#[test]
fn move_chart_updates_anchor() {
    let buf = std::fs::read("../../tests/graph.xlsx").unwrap();
    let mut wb = Workbook::from_file(&buf, "graph".to_string()).unwrap();

    // The chart is anchored on the first sheet in graph.xlsx.
    let sheet_idx = 0usize;
    let chart_id = {
        let ws = wb.get_sheet_by_idx(sheet_idx).unwrap();
        ws.get_charts()
            .first()
            .expect("a chart should be present on sheet 0")
            .chart_id
            .clone()
    };

    // Move the chart so its top-left anchors at B3 (row 2, col 1).
    let effect = wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::MoveChart(MoveChart {
            sheet_idx,
            chart_id: chart_id.clone(),
            from_row: 2,
            from_col: 1,
            from_col_off: 0,
            from_row_off: 0,
            to_row: 12,
            to_col: 7,
            to_col_off: 0,
            to_row_off: 0,
        })],
        undoable: true,
        init: false,
    }));
    assert!(matches!(
        effect.status,
        crate::edit_action::StatusCode::Ok(_)
    ));

    let ws = wb.get_sheet_by_idx(sheet_idx).unwrap();
    let charts = ws.get_charts();
    let c = charts.iter().find(|c| c.chart_id == chart_id).unwrap();
    assert_eq!((c.from_row, c.from_col), (2, 1), "anchor should have moved");
    assert_eq!((c.to_row, c.to_col), (12, 7));
    drop(ws);

    // Save to xlsx and reload: the chart survives the controller round-trip
    // (Stage 3b) at its moved anchor.
    let bytes = wb.save().unwrap();
    let wb2 = Workbook::from_file(&bytes, "reloaded".to_string()).unwrap();
    let ws2 = wb2.get_sheet_by_idx(sheet_idx).unwrap();
    let charts2 = ws2.get_charts();
    assert_eq!(charts2.len(), 1, "chart should survive save/reload");
    let c2 = &charts2[0];
    assert_eq!(c2.chart_type, "col", "chart data preserved");
    assert_eq!((c2.from_row, c2.from_col), (2, 1), "moved anchor persisted");
    assert_eq!((c2.to_row, c2.to_col), (12, 7));
    assert_eq!(c2.series.len(), 3);
}

#[test]
fn data_validation_round_trip() {
    use logisheets_workbook::prelude::{
        CtDataValidation, CtDataValidations, PlainTextString, StDataValidationErrorStyle,
        StDataValidationImeMode, StDataValidationOperator, StDataValidationType, Wb, write,
    };

    // Start from a valid empty workbook, then inject a data-validation rule at
    // the workbook layer to simulate an xlsx authored by Excel.
    let base = Workbook::default().save().unwrap();
    let mut raw = Wb::from_file(&base).unwrap();
    let dv = CtDataValidations {
        data_validations: vec![CtDataValidation {
            formula1: Some(PlainTextString {
                value: "\"Apple,Banana,Cherry\"".to_string(),
                space: None,
            }),
            formula2: None,
            ty: StDataValidationType::List,
            error_style: StDataValidationErrorStyle::Stop,
            ime_mode: StDataValidationImeMode::NoControl,
            operator: StDataValidationOperator::Between,
            blank: true,
            show_drop_down: false,
            show_input_message: false,
            show_error_message: true,
            prompt_title: None,
            prompt: None,
            sqref: "A1:A10".to_string(),
        }],
        disable_prompts: false,
        x_window: None,
        y_window: None,
        count: 1,
    };
    raw.xl
        .worksheets
        .values_mut()
        .next()
        .unwrap()
        .worksheet_part
        .data_validations = Some(dv);
    let input = write(raw).unwrap();

    // Round-trip through the controller: load, save, reload.
    let wb = Workbook::from_file(&input, "dv".to_string()).unwrap();
    let out = wb.save().unwrap();

    // The validation must survive (previously the saver dropped it: wrote None).
    let reloaded = Wb::from_file(&out).unwrap();
    let ws = reloaded.xl.worksheets.values().next().unwrap();
    let dv2 = ws
        .worksheet_part
        .data_validations
        .as_ref()
        .expect("data validation should survive the controller round trip");
    assert_eq!(dv2.data_validations.len(), 1);
    assert_eq!(dv2.data_validations[0].sqref, "A1:A10");
    assert!(matches!(
        dv2.data_validations[0].ty,
        StDataValidationType::List
    ));
    assert_eq!(
        dv2.data_validations[0].formula1.as_ref().unwrap().value,
        "\"Apple,Banana,Cherry\""
    );
}

#[test]
fn data_validation_flags_invalid_cell() {
    use crate::controller::display::Value;
    use crate::edit_action::CellInput;
    use crate::sid_assigner::ShadowKind;
    use logisheets_base::CellId;
    use logisheets_workbook::prelude::{
        CtDataValidation, CtDataValidations, PlainTextString, StDataValidationErrorStyle,
        StDataValidationImeMode, StDataValidationOperator, StDataValidationType, Wb, write,
    };

    // Author an xlsx that already contains A1="Apple" (valid) and A2="Zebra"
    // (invalid) so the values are present at load time — shadows are only
    // materialized on load (from_file), not on later edits.
    let mut authored = Workbook::default();
    authored.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![
            EditPayload::CellInput(CellInput {
                sheet_idx: 0,
                row: 0,
                col: 0,
                content: "Apple".to_string(),
            }),
            EditPayload::CellInput(CellInput {
                sheet_idx: 0,
                row: 1,
                col: 0,
                content: "Zebra".to_string(),
            }),
        ],
        undoable: false,
        init: false,
    }));
    let base = authored.save().unwrap();

    // Inject a list rule on A1:A10 accepting only Apple/Banana.
    let mut raw = Wb::from_file(&base).unwrap();
    let dv = CtDataValidations {
        data_validations: vec![CtDataValidation {
            formula1: Some(PlainTextString {
                value: "\"Apple,Banana\"".to_string(),
                space: None,
            }),
            formula2: None,
            ty: StDataValidationType::List,
            error_style: StDataValidationErrorStyle::Stop,
            ime_mode: StDataValidationImeMode::NoControl,
            operator: StDataValidationOperator::Between,
            blank: true,
            show_drop_down: false,
            show_input_message: false,
            show_error_message: true,
            prompt_title: None,
            prompt: None,
            sqref: "A1:A10".to_string(),
        }],
        disable_prompts: false,
        x_window: None,
        y_window: None,
        count: 1,
    };
    raw.xl
        .worksheets
        .values_mut()
        .next()
        .unwrap()
        .worksheet_part
        .data_validations = Some(dv);
    let input = write(raw).unwrap();

    // Loading materializes the validation shadows for the non-empty cells.
    let mut wb = Workbook::from_file(&input, "dv".to_string()).unwrap();

    let mut read = |row: usize| -> Value {
        let scid = wb
            .get_shadow_cell_id(0, row, 0, ShadowKind::Validation)
            .unwrap();
        let id = match scid.cell_id {
            CellId::EphemeralCell(i) => i,
            _ => panic!("expected an ephemeral shadow cell"),
        };
        wb.get_shadow_info_by_id(id).unwrap().value
    };
    assert!(
        matches!(read(0), Value::Bool(true)),
        "Apple should be valid"
    );
    assert!(
        matches!(read(1), Value::Bool(false)),
        "Zebra should be invalid"
    );
}

#[test]
fn get_cell_list_validation_reads_list_type() {
    use crate::data_validation_manager::ListValidation;
    use logisheets_workbook::prelude::{
        CtDataValidation, CtDataValidations, PlainTextString, StDataValidationErrorStyle,
        StDataValidationImeMode, StDataValidationOperator, StDataValidationType, Wb, write,
    };

    let mk = |ty: StDataValidationType, f1: &str, sqref: &str| CtDataValidation {
        formula1: Some(PlainTextString {
            value: f1.to_string(),
            space: None,
        }),
        formula2: None,
        ty,
        error_style: StDataValidationErrorStyle::Stop,
        ime_mode: StDataValidationImeMode::NoControl,
        operator: StDataValidationOperator::Between,
        blank: true,
        show_drop_down: true,
        show_input_message: false,
        show_error_message: false,
        prompt_title: None,
        prompt: None,
        sqref: sqref.to_string(),
    };

    let base = Workbook::default().save().unwrap();
    let mut raw = Wb::from_file(&base).unwrap();
    let dv = CtDataValidations {
        data_validations: vec![
            // Inline list on A1:A10.
            mk(
                StDataValidationType::List,
                "\"East,West,North,South\"",
                "A1:A10",
            ),
            // Range-reference list on C1.
            mk(StDataValidationType::List, "$G$1:$G$4", "C1"),
            // A non-list rule that must be ignored on B1.
            mk(StDataValidationType::Whole, "1", "B1"),
        ],
        disable_prompts: false,
        x_window: None,
        y_window: None,
        count: 3,
    };
    raw.xl
        .worksheets
        .values_mut()
        .next()
        .unwrap()
        .worksheet_part
        .data_validations = Some(dv);
    let input = write(raw).unwrap();
    let wb = Workbook::from_file(&input, "dv".to_string()).unwrap();

    // Inline list: A1 (row 0, col 0) is covered.
    assert_eq!(
        wb.get_cell_list_validation(0, 0, 0),
        Some(ListValidation::Inline(vec![
            "East".into(),
            "West".into(),
            "North".into(),
            "South".into(),
        ]))
    );
    // Still covered lower in the sqref range (A10).
    assert!(matches!(
        wb.get_cell_list_validation(0, 9, 0),
        Some(ListValidation::Inline(_))
    ));
    // Range reference comes back raw for the caller to resolve.
    assert_eq!(
        wb.get_cell_list_validation(0, 0, 2),
        Some(ListValidation::Reference("$G$1:$G$4".to_string()))
    );
    // A non-list rule is not surfaced.
    assert_eq!(wb.get_cell_list_validation(0, 0, 1), None);
    // A cell outside every sqref has no validation.
    assert_eq!(wb.get_cell_list_validation(0, 5, 5), None);
}

#[test]
fn cell_image_round_trip() {
    use crate::image_manager::base64;

    // A tiny 1x1 transparent PNG.
    let png: &[u8] = &[
        0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x01, 0x02, 0x03, 0xFD, 0xFE, 0xFF,
    ];
    let data_b64 = base64::encode(png);

    let mut wb = Workbook::default();
    let effect = wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::SetCellImage(SetCellImage {
            sheet_idx: 0,
            row: 2,
            col: 3,
            image_id: "img-a".to_string(),
            format: "png".to_string(),
            data: data_b64.clone(),
        })],
        undoable: true,
        init: false,
    }));
    assert!(matches!(
        effect.status,
        crate::edit_action::StatusCode::Ok(_)
    ));

    // The image is visible via the display API.
    let ws = wb.get_sheet_by_idx(0).unwrap();
    let imgs = ws.get_cell_images();
    assert_eq!(imgs.len(), 1);
    assert_eq!((imgs[0].row, imgs[0].col), (2, 3));
    assert_eq!(imgs[0].format, "png");
    assert_eq!(base64::decode(&imgs[0].data).unwrap(), png);
    drop(ws);

    // Save to xlsx and reload — the image survives the round trip.
    let bytes = wb.save().unwrap();
    let wb2 = Workbook::from_file(&bytes, "reloaded".to_string()).unwrap();
    let ws2 = wb2.get_sheet_by_idx(0).unwrap();
    let imgs2 = ws2.get_cell_images();
    assert_eq!(imgs2.len(), 1, "image should survive save/load");
    assert_eq!((imgs2[0].row, imgs2[0].col), (2, 3));
    assert_eq!(imgs2[0].format, "png");
    assert_eq!(base64::decode(&imgs2[0].data).unwrap(), png);

    // Undo removes it.
    wb.handle_action(EditAction::Undo);
    let ws = wb.get_sheet_by_idx(0).unwrap();
    assert_eq!(
        ws.get_cell_images().len(),
        0,
        "undo should remove the image"
    );
    drop(ws);

    // Delete payload also removes it (redo first to bring it back).
    wb.handle_action(EditAction::Redo);
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::DeleteCellImage(DeleteCellImage {
            sheet_idx: 0,
            row: 2,
            col: 3,
        })],
        undoable: true,
        init: false,
    }));
    let ws = wb.get_sheet_by_idx(0).unwrap();
    assert_eq!(
        ws.get_cell_images().len(),
        0,
        "delete should remove the image"
    );
}

#[test]
fn new_workbook() {
    let mut wb = Workbook::default();
    let ws = wb.get_sheet_by_idx(0).unwrap();

    ws.get_cell_position(100, 100).unwrap();

    let empty_display_window = ws.get_display_window(0, 0, 100, 100).unwrap();
    let row_cnt = empty_display_window.rows.len();
    let col_cnt = empty_display_window.cols.len();
    let cell_cnt = empty_display_window.cells.len();
    assert!(row_cnt >= 100);
    assert!(col_cnt >= 100);
    assert_eq!(row_cnt * col_cnt, cell_cnt);
    assert_eq!(empty_display_window.rows[0].idx, 0);
    assert_eq!(empty_display_window.cols[0].idx, 0);

    let empty_display_resp = ws.get_display_window_response(0., 0., 100., 100.).unwrap();
    assert!(empty_display_resp.window.cells.len() > 0);
    assert!(empty_display_resp.window.rows.len() > 0);
    assert!(empty_display_resp.window.cols.len() > 0);

    assert_eq!(empty_display_resp.window.rows.get(0).unwrap().idx, 0);
    assert_eq!(empty_display_resp.window.cols.get(0).unwrap().idx, 0);
    let v = empty_display_resp
        .window
        .cols
        .into_iter()
        .fold(0., |p, c| return p + c.width);
    assert!(v > 100.);

    let result = wb.handle_action(crate::EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::SheetRename(SheetRename {
            old_name: Some("Sheet1".to_string()),
            new_name: "abcd".to_string(),
            idx: None,
        })],
        undoable: true,
        init: false,
    }));

    match result.status {
        crate::edit_action::StatusCode::Ok(workbook_update_type) => {
            println!("{:?}", workbook_update_type);
            assert!(matches!(workbook_update_type, WorkbookUpdateType::Sheet));
        }
        crate::edit_action::StatusCode::Err(e) => panic!("{:?}", e),
    }
}

#[test]
fn create_block() {
    let mut wb = Workbook::default();
    let id = wb.get_available_block_id(0).unwrap();
    let payload_action = PayloadsAction {
        payloads: vec![EditPayload::CreateBlock(CreateBlock {
            sheet_idx: 0,
            id,
            master_row: 1,
            master_col: 1,
            row_cnt: 3,
            col_cnt: 3,
            owner: None,
            modify_policy: None,
        })],
        undoable: false,
        init: false,
    };
    let _ = wb.handle_action(EditAction::Payloads(payload_action));
    let ws = wb.get_sheet_by_idx(0).unwrap();
    let _ = ws.get_display_window(0, 0, 10, 10).unwrap();
    ws.get_cell_position(1, 1).unwrap();
    ws.get_cell_position(3, 3).unwrap();
    let resp = ws.get_display_window_response(0., 0., 100., 100.).unwrap();
    assert_eq!(resp.window.blocks.len(), 1);
}

#[test]
fn get_col_style() {
    let mut wb = Workbook::default();
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::LineStyleUpdate(LineStyleUpdate {
            sheet_idx: 0,
            from: 0,
            to: 1,
            row: true,
            ty: StyleUpdateType {
                set_num_fmt: Some("0.00".to_string()),
                ..Default::default()
            },
        })],
        undoable: true,
        init: false,
    }));
    let ws = wb.get_sheet_by_idx(0).unwrap();
    let style = ws.get_style(0, 0).unwrap();
    assert_eq!(style.formatter, "0.00");
}

#[test]
fn overwrite_formula_with_plain_value() {
    use crate::controller::display::Value;
    use crate::edit_action::CellInput;

    let mut wb = Workbook::default();

    // Write a formula into A1.
    let r = wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::CellInput(CellInput {
            sheet_idx: 0,
            row: 0,
            col: 0,
            content: "=1+1".to_string(),
        })],
        undoable: true,
        init: false,
    }));
    assert!(matches!(r.status, crate::edit_action::StatusCode::Ok(_)));
    let ws = wb.get_sheet_by_idx(0).unwrap();
    assert_eq!(ws.get_formula(0, 0).unwrap(), "1 + 1");
    assert!(matches!(ws.get_value(0, 0).unwrap(), Value::Number(n) if (n - 2.0).abs() < 1e-9));

    // Overwrite with a plain number. The formula must be cleared,
    // otherwise the next recalc re-evaluates 1+1 over the typed "5".
    let r = wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::CellInput(CellInput {
            sheet_idx: 0,
            row: 0,
            col: 0,
            content: "5".to_string(),
        })],
        undoable: true,
        init: false,
    }));
    assert!(matches!(r.status, crate::edit_action::StatusCode::Ok(_)));
    let ws = wb.get_sheet_by_idx(0).unwrap();
    assert_eq!(ws.get_formula(0, 0).unwrap(), "");
    match ws.get_value(0, 0).unwrap() {
        Value::Number(n) => assert!((n - 5.0).abs() < 1e-9, "got {}", n),
        v => panic!("expected Number(5), got {:?}", v),
    }
}

// A range link redirects a source range (A1:A2) to a backing block's column.
// The seller's formula references the LITERAL A1:A2, yet:
//   - it reads the block (redirect at range-id resolution),
//   - editing the block recomputes it (the dependency edge is really in the
//     graph, so recalc triggers — not just a lazy value alias),
//   - growing the block (interior insert) makes the aggregate track new rows,
//   - the source A1:A2 cells are never touched (non-destructive facade).
#[test]
fn range_link_redirects_to_block_and_tracks_growth() {
    use crate::controller::display::Value;
    use crate::edit_action::{BindFormSchema, CellInput, InsertRowsInBlock};

    let mut wb = Workbook::default();
    let bid = wb.get_available_block_id(0).unwrap();

    // Backing block: 2 rows x 1 col at D1 (row 0, col 3), seeded 10 / 20, WITH a
    // form schema (a real record — growth tracking rides on the block-field dep).
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![
            EditPayload::CreateBlock(CreateBlock {
                sheet_idx: 0,
                id: bid,
                master_row: 0,
                master_col: 3,
                row_cnt: 2,
                col_cnt: 1,
                owner: None,
                modify_policy: None,
            }),
            EditPayload::BindFormSchema(BindFormSchema {
                ref_name: "rec".into(), sheet_idx: 0, block_id: bid,
                field_from: 0, key_idx: 0, fields: vec!["v".into()],
                render_ids: vec!["r0".into()], row: true,
                field_formulas: vec![], validation_formulas: vec![], editability_formulas: vec![],
            }),
            EditPayload::CellInput(CellInput {
                sheet_idx: 0,
                row: 0,
                col: 3,
                content: "10".to_string(),
            }),
            EditPayload::CellInput(CellInput {
                sheet_idx: 0,
                row: 1,
                col: 3,
                content: "20".to_string(),
            }),
        ],
        undoable: false,
        init: false,
    }));

    // Link A1:A2 -> the block's column (block rows 0..=1, col 0).
    wb.test_add_range_link(0, (0, 0, 1, 0), bid, 0, 1, 0);

    // Seller formula references the literal A1:A2 -> resolves to the block.
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::CellInput(CellInput {
            sheet_idx: 0,
            row: 0,
            col: 4,
            content: "=SUM(A1:A2)".to_string(),
        })],
        undoable: false,
        init: false,
    }));
    {
        let ws = wb.get_sheet_by_idx(0).unwrap();
        assert!(
            matches!(ws.get_value(0, 4).unwrap(), Value::Number(n) if (n - 30.0).abs() < 1e-9),
            "linked SUM(A1:A2) should read the block (30), got {:?}",
            ws.get_value(0, 4).unwrap()
        );
        // The source A1 cell was never written — the link is non-destructive.
        assert!(matches!(ws.get_value(0, 0).unwrap(), Value::Empty));
    }

    // Edit a block cell -> the linked formula recomputes.
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::CellInput(CellInput {
            sheet_idx: 0,
            row: 0,
            col: 3,
            content: "100".to_string(),
        })],
        undoable: false,
        init: false,
    }));
    {
        let ws = wb.get_sheet_by_idx(0).unwrap();
        assert!(
            matches!(ws.get_value(0, 4).unwrap(), Value::Number(n) if (n - 120.0).abs() < 1e-9),
            "SUM should recompute after the block changed (120), got {:?}",
            ws.get_value(0, 4).unwrap()
        );
    }

    // Grow the block 2 -> 3 via interior insert, fill the new row.
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::InsertRowsInBlock(InsertRowsInBlock {
            sheet_idx: 0,
            block_id: bid,
            start: 1,
            cnt: 1,
        })],
        undoable: false,
        init: false,
    }));
    // After interior insert: D1=100 (old r0), D2=new (empty), D3=20 (old r1).
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::CellInput(CellInput {
            sheet_idx: 0,
            row: 1,
            col: 3,
            content: "5".to_string(),
        })],
        undoable: false,
        init: false,
    }));
    {
        let ws = wb.get_sheet_by_idx(0).unwrap();
        assert!(
            matches!(ws.get_value(0, 4).unwrap(), Value::Number(n) if (n - 125.0).abs() < 1e-9),
            "SUM should include the grown row (100+5+20=125), got {:?}",
            ws.get_value(0, 4).unwrap()
        );
    }
}

// The CreateLink edit payload, driven through the public API, for the real app
// flow: the seller's SUM(A1:A2) formula ALREADY exists (reading literal cells),
// THEN the user links A1:A2 to a block. The existing formula must redirect to the
// block (id remap + recalc), and growth must track — all via handle_action.
#[test]
fn create_link_payload_redirects_existing_formula() {
    use crate::controller::display::Value;
    use crate::edit_action::{BindFormSchema, CellInput, CreateLink, InsertRowsInBlock};

    let mut wb = Workbook::default();
    let bid = wb.get_available_block_id(0).unwrap();

    // Setup: A1=1, A2=2, E1=SUM(A1:A2) (reads the literal cells => 3); plus a
    // separate backing block (with a form schema — a real record) at D1:D2
    // seeded 10 / 20.
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![
            EditPayload::CellInput(CellInput { sheet_idx: 0, row: 0, col: 0, content: "1".to_string() }),
            EditPayload::CellInput(CellInput { sheet_idx: 0, row: 1, col: 0, content: "2".to_string() }),
            EditPayload::CellInput(CellInput { sheet_idx: 0, row: 0, col: 4, content: "=SUM(A1:A2)".to_string() }),
            EditPayload::CreateBlock(CreateBlock {
                sheet_idx: 0, id: bid, master_row: 0, master_col: 3,
                row_cnt: 2, col_cnt: 1, owner: None, modify_policy: None,
            }),
            EditPayload::BindFormSchema(BindFormSchema {
                ref_name: "rec".into(), sheet_idx: 0, block_id: bid,
                field_from: 0, key_idx: 0, fields: vec!["v".into()],
                render_ids: vec!["r0".into()], row: true,
                field_formulas: vec![], validation_formulas: vec![], editability_formulas: vec![],
            }),
            EditPayload::CellInput(CellInput { sheet_idx: 0, row: 0, col: 3, content: "10".to_string() }),
            EditPayload::CellInput(CellInput { sheet_idx: 0, row: 1, col: 3, content: "20".to_string() }),
        ],
        undoable: false,
        init: false,
    }));
    {
        let ws = wb.get_sheet_by_idx(0).unwrap();
        assert!(
            matches!(ws.get_value(0, 4).unwrap(), Value::Number(n) if (n - 3.0).abs() < 1e-9),
            "before link, SUM(A1:A2) reads the literal cells (3), got {:?}",
            ws.get_value(0, 4).unwrap()
        );
    }

    // Link A1:A2 -> the block. The existing SUM must redirect to the block.
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::CreateLink(CreateLink {
            sheet_idx: 0,
            master_row: 0,
            master_col: 0,
            row_cnt: 2,
            col_cnt: 1,
            block_id: bid,
            block_sheet_idx: None,
        })],
        undoable: false,
        init: false,
    }));
    {
        let ws = wb.get_sheet_by_idx(0).unwrap();
        assert!(
            matches!(ws.get_value(0, 4).unwrap(), Value::Number(n) if (n - 30.0).abs() < 1e-9),
            "after link, the existing SUM redirects to the block (30), got {:?}",
            ws.get_value(0, 4).unwrap()
        );
        // Source cells are untouched — still 1, non-destructive.
        assert!(matches!(ws.get_value(0, 0).unwrap(), Value::Number(n) if (n - 1.0).abs() < 1e-9));
    }

    // Grow the block via interior insert + fill -> the linked SUM tracks it.
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![
            EditPayload::InsertRowsInBlock(InsertRowsInBlock {
                sheet_idx: 0, block_id: bid, start: 1, cnt: 1,
            }),
            EditPayload::CellInput(CellInput { sheet_idx: 0, row: 1, col: 3, content: "5".to_string() }),
        ],
        undoable: false,
        init: false,
    }));
    {
        let ws = wb.get_sheet_by_idx(0).unwrap();
        assert!(
            matches!(ws.get_value(0, 4).unwrap(), Value::Number(n) if (n - 35.0).abs() < 1e-9),
            "linked SUM tracks the grown block (10+5+20=35), got {:?}",
            ws.get_value(0, 4).unwrap()
        );
    }
}

// Repro of the reported bug: SUM over a range LINKED to a block (block has MORE
// rows than the source) still read the literal source cells. Covers BOTH orders:
// formula created BEFORE the link, and formula created AFTER the link.
#[test]
fn linked_range_size_mismatch_reads_block_both_orders() {
    use crate::controller::display::Value;
    use crate::edit_action::{CellInput, CreateLink};

    let sum_of_block = 1.0 + 3.0 + 4.0 + 5.0 + 6.0 + 7.0; // 26

    // Helper: build a workbook with a 6-row block at D1:D6 (1,3,4,5,6,7) and
    // literal 1,2,3,4 at A1:A4. `formula_first` controls the order of creating
    // =SUM(A1:A4) relative to CreateLink(A1:A4 -> block).
    let build = |formula_first: bool| -> Workbook {
        let mut wb = Workbook::default();
        let bid = wb.get_available_block_id(0).unwrap();
        let mut payloads = vec![
            EditPayload::CreateBlock(CreateBlock {
                sheet_idx: 0, id: bid, master_row: 0, master_col: 3,
                row_cnt: 6, col_cnt: 1, owner: None, modify_policy: None,
            }),
        ];
        for (i, v) in [1, 3, 4, 5, 6, 7].iter().enumerate() {
            payloads.push(EditPayload::CellInput(CellInput {
                sheet_idx: 0, row: i, col: 3, content: v.to_string(),
            }));
        }
        for (i, v) in [1, 2, 3, 4].iter().enumerate() {
            payloads.push(EditPayload::CellInput(CellInput {
                sheet_idx: 0, row: i, col: 0, content: v.to_string(),
            }));
        }
        let formula = EditPayload::CellInput(CellInput {
            sheet_idx: 0, row: 0, col: 6, content: "=SUM(A1:A4)".to_string(),
        });
        let link = EditPayload::CreateLink(CreateLink {
            sheet_idx: 0, master_row: 0, master_col: 0, row_cnt: 4, col_cnt: 1, block_id: bid, block_sheet_idx: None,
        });
        if formula_first {
            payloads.push(formula);
            payloads.push(link);
        } else {
            payloads.push(link);
            payloads.push(formula);
        }
        wb.handle_action(EditAction::Payloads(PayloadsAction {
            payloads, undoable: false, init: false,
        }));
        wb
    };

    for formula_first in [true, false] {
        let wb = build(formula_first);
        let ws = wb.get_sheet_by_idx(0).unwrap();
        let got = ws.get_value(0, 6).unwrap();
        assert!(
            matches!(got, Value::Number(n) if (n - sum_of_block).abs() < 1e-9),
            "formula_first={formula_first}: SUM(A1:A4) linked to the 6-row block \
             should read the block ({sum_of_block}), got {:?}",
            got
        );
    }
}

// Repro of the reported bug's real cause: a MULTI-column range is linked to a
// multi-column block, but the user SUMs only ONE column of it (a sub-range). The
// reference should map to the block's corresponding column.
#[test]
fn linked_multicol_subcolumn_reference_reads_block_column() {
    use crate::controller::display::Value;
    use crate::edit_action::{CellInput, CreateLink};

    let mut wb = Workbook::default();
    let bid = wb.get_available_block_id(0).unwrap();

    // Block D1:E6 (2 cols x 6 rows): col D = 10,20,30,40,50,60; col E = 1,3,4,5,6,7.
    let mut payloads = vec![EditPayload::CreateBlock(CreateBlock {
        sheet_idx: 0, id: bid, master_row: 0, master_col: 3,
        row_cnt: 6, col_cnt: 2, owner: None, modify_policy: None,
    })];
    for (i, v) in [10, 20, 30, 40, 50, 60].iter().enumerate() {
        payloads.push(EditPayload::CellInput(CellInput {
            sheet_idx: 0, row: i, col: 3, content: v.to_string(),
        }));
    }
    for (i, v) in [1, 3, 4, 5, 6, 7].iter().enumerate() {
        payloads.push(EditPayload::CellInput(CellInput {
            sheet_idx: 0, row: i, col: 4, content: v.to_string(),
        }));
    }
    // Literal 1,2,3,4 in A1:B4 (source), then link A1:B4 (2 cols) -> block.
    for (i, v) in [1, 2, 3, 4].iter().enumerate() {
        payloads.push(EditPayload::CellInput(CellInput {
            sheet_idx: 0, row: i, col: 0, content: (v * 100).to_string(),
        }));
        payloads.push(EditPayload::CellInput(CellInput {
            sheet_idx: 0, row: i, col: 1, content: v.to_string(),
        }));
    }
    // =SUM(B1:B4): only the 2nd column of the linked A1:B4 range.
    payloads.push(EditPayload::CellInput(CellInput {
        sheet_idx: 0, row: 0, col: 6, content: "=SUM(B1:B4)".to_string(),
    }));
    payloads.push(EditPayload::CreateLink(CreateLink {
        sheet_idx: 0, master_row: 0, master_col: 0, row_cnt: 4, col_cnt: 2, block_id: bid, block_sheet_idx: None,
    }));
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads, undoable: false, init: false,
    }));

    // Desired: B (2nd link col) maps to block col E = 1+3+4+5+6+7 = 26.
    let ws = wb.get_sheet_by_idx(0).unwrap();
    let got = ws.get_value(0, 6).unwrap();
    assert!(
        matches!(got, Value::Number(n) if (n - 26.0).abs() < 1e-9),
        "SUM(B1:B4), a sub-column of linked A1:B4, should read block col E (26), got {:?}",
        got
    );
}

// CROSS-SHEET link: the seller's `SUM(A1:A2)` on sheet 0 is backed by a schema'd
// block on sheet 1 (the hidden `__douyoushu_io__` pattern). The formula stays
// native on its own sheet; value + growth + save/load all track the other sheet.
#[test]
fn cross_sheet_linked_column_tracks_block_and_survives_save_load() {
    use crate::controller::display::Value;
    use crate::edit_action::{
        BindFormSchema, CellInput, CreateLink, CreateSheet, InsertRowsInBlock,
    };

    let mut wb = Workbook::default();
    // Sheet 1 ("io") holds the backing block.
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::CreateSheet(CreateSheet {
            idx: 1,
            new_name: "io".into(),
        })],
        undoable: false,
        init: false,
    }));
    let bid = wb.get_available_block_id(1).unwrap();
    // Sheet 1: schema'd block D1:D2 = 10, 20. Sheet 0: =SUM(A1:A2) cross-sheet
    // linked to that block.
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![
            EditPayload::CreateBlock(CreateBlock {
                sheet_idx: 1, id: bid, master_row: 0, master_col: 3,
                row_cnt: 2, col_cnt: 1, owner: None, modify_policy: None,
            }),
            EditPayload::BindFormSchema(BindFormSchema {
                ref_name: "rec".into(), sheet_idx: 1, block_id: bid,
                field_from: 0, key_idx: 0, fields: vec!["v".into()],
                render_ids: vec!["r0".into()], row: true,
                field_formulas: vec![], validation_formulas: vec![], editability_formulas: vec![],
            }),
            EditPayload::CellInput(CellInput { sheet_idx: 1, row: 0, col: 3, content: "10".into() }),
            EditPayload::CellInput(CellInput { sheet_idx: 1, row: 1, col: 3, content: "20".into() }),
            EditPayload::CellInput(CellInput { sheet_idx: 0, row: 0, col: 6, content: "=SUM(A1:A2)".into() }),
            EditPayload::CreateLink(CreateLink {
                sheet_idx: 0, master_row: 0, master_col: 0, row_cnt: 2, col_cnt: 1,
                block_id: bid, block_sheet_idx: Some(1),
            }),
        ],
        undoable: false, init: false,
    }));
    let val = |wb: &Workbook| wb.get_sheet_by_idx(0).unwrap().get_value(0, 6).unwrap();
    assert!(matches!(val(&wb), Value::Number(n) if (n - 30.0).abs() < 1e-9),
        "cross-sheet SUM reads the block on sheet 1 (30), got {:?}", val(&wb));
    // The facade A1 on sheet 0 stays empty (non-destructive).
    assert!(matches!(wb.get_sheet_by_idx(0).unwrap().get_value(0, 0).unwrap(), Value::Empty));

    // Append a row on sheet 1 + fill → the sheet-0 SUM tracks.
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![
            EditPayload::InsertRowsInBlock(InsertRowsInBlock { sheet_idx: 1, block_id: bid, start: 2, cnt: 1 }),
            EditPayload::CellInput(CellInput { sheet_idx: 1, row: 2, col: 3, content: "7".into() }),
        ],
        undoable: false, init: false,
    }));
    assert!(matches!(val(&wb), Value::Number(n) if (n - 37.0).abs() < 1e-9),
        "cross-sheet SUM tracks the appended block row (37), got {:?}", val(&wb));
    // A later edit of the appended cell (separate txn) recomputes across sheets.
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::CellInput(CellInput { sheet_idx: 1, row: 2, col: 3, content: "100".into() })],
        undoable: false, init: false,
    }));
    assert!(matches!(val(&wb), Value::Number(n) if (n - 130.0).abs() < 1e-9),
        "cross-sheet later edit recomputes (130), got {:?}", val(&wb));

    // Save/load keeps the cross-sheet link (formula stays native on sheet 0).
    let bytes = wb.save().expect("save");
    let wb2 = Workbook::from_file(&bytes, "reloaded".into()).expect("load");
    let ws0 = wb2.get_sheet_by_idx(0).unwrap();
    assert_eq!(ws0.get_links().len(), 1, "cross-sheet link restored on load");
    assert_eq!(ws0.get_formula(0, 6).unwrap(), "SUM(A1:A2)");
    assert!(matches!(ws0.get_value(0, 6).unwrap(), Value::Number(n) if (n - 130.0).abs() < 1e-9),
        "cross-sheet value survives save/load (130)");
}

// A link survives save -> load: the link map is persisted in the LogiSheets
// ooxml part, the formula keeps its FACADE reference (`SUM(A1:A2)`, not the
// block's coords), and value + growth still work after the round-trip.
#[test]
fn link_survives_save_load() {
    use crate::controller::display::Value;
    use crate::edit_action::{BindFormSchema, CellInput, CreateLink, InsertRowsInBlock};

    let mut wb = Workbook::default();
    let bid = wb.get_available_block_id(0).unwrap();
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![
            EditPayload::CreateBlock(CreateBlock {
                sheet_idx: 0, id: bid, master_row: 0, master_col: 3,
                row_cnt: 2, col_cnt: 1, owner: None, modify_policy: None,
            }),
            EditPayload::BindFormSchema(BindFormSchema {
                ref_name: "rec".into(), sheet_idx: 0, block_id: bid,
                field_from: 0, key_idx: 0, fields: vec!["v".into()],
                render_ids: vec!["r0".into()], row: true,
                field_formulas: vec![], validation_formulas: vec![], editability_formulas: vec![],
            }),
            EditPayload::CellInput(CellInput { sheet_idx: 0, row: 0, col: 3, content: "10".into() }),
            EditPayload::CellInput(CellInput { sheet_idx: 0, row: 1, col: 3, content: "20".into() }),
            EditPayload::CellInput(CellInput { sheet_idx: 0, row: 0, col: 5, content: "=SUM(A1:A2)".into() }),
            EditPayload::CreateLink(CreateLink {
                sheet_idx: 0, master_row: 0, master_col: 0, row_cnt: 2, col_cnt: 1, block_id: bid, block_sheet_idx: None,
            }),
        ],
        undoable: false, init: false,
    }));
    assert!(matches!(wb.get_sheet_by_idx(0).unwrap().get_value(0, 5).unwrap(),
        Value::Number(n) if (n - 30.0).abs() < 1e-9));

    let bytes = wb.save().expect("save");
    let mut wb2 = Workbook::from_file(&bytes, "reloaded".into()).expect("load");
    let ws2 = wb2.get_sheet_by_idx(0).unwrap();
    // The link persisted...
    assert_eq!(ws2.get_links().len(), 1, "the link should be restored on load");
    // ...the formula kept its facade reference (NOT baked to the block coords)...
    assert_eq!(ws2.get_formula(0, 5).unwrap(), "SUM(A1:A2)");
    // ...it still reads the block, and the facade A1:A2 stays empty.
    assert!(matches!(ws2.get_value(0, 5).unwrap(), Value::Number(n) if (n - 30.0).abs() < 1e-9));
    assert!(matches!(ws2.get_value(0, 0).unwrap(), Value::Empty));

    // Growth still works after load.
    wb2.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![
            EditPayload::InsertRowsInBlock(InsertRowsInBlock { sheet_idx: 0, block_id: bid, start: 2, cnt: 1 }),
            EditPayload::CellInput(CellInput { sheet_idx: 0, row: 2, col: 3, content: "7".into() }),
        ],
        undoable: false, init: false,
    }));
    assert!(matches!(wb2.get_sheet_by_idx(0).unwrap().get_value(0, 5).unwrap(),
        Value::Number(n) if (n - 37.0).abs() < 1e-9));
}

// A linked record column must follow the block when it grows at the TAIL
// (a new record appended after the last row), not just on interior inserts.
#[test]
fn linked_column_tracks_tail_append() {
    use crate::controller::display::Value;
    use crate::edit_action::{CellInput, CreateLink, InsertRowsInBlock};

    use crate::edit_action::BindFormSchema;
    let mut wb = Workbook::default();
    let bid = wb.get_available_block_id(0).unwrap();
    // Block D1:D2 = 10, 20, WITH a form schema (a real record block). Link
    // A1:A2 -> it. =SUM(A1:A2) reads the block = 30.
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![
            EditPayload::CreateBlock(CreateBlock {
                sheet_idx: 0, id: bid, master_row: 0, master_col: 3,
                row_cnt: 2, col_cnt: 1, owner: None, modify_policy: None,
            }),
            EditPayload::BindFormSchema(BindFormSchema {
                ref_name: "rec".into(), sheet_idx: 0, block_id: bid,
                field_from: 0, key_idx: 0, fields: vec!["v".into()],
                render_ids: vec!["r0".into()], row: true,
                field_formulas: vec![], validation_formulas: vec![], editability_formulas: vec![],
            }),
            EditPayload::CellInput(CellInput { sheet_idx: 0, row: 0, col: 3, content: "10".into() }),
            EditPayload::CellInput(CellInput { sheet_idx: 0, row: 1, col: 3, content: "20".into() }),
            EditPayload::CellInput(CellInput { sheet_idx: 0, row: 0, col: 5, content: "=SUM(A1:A2)".into() }),
            EditPayload::CreateLink(CreateLink {
                sheet_idx: 0, master_row: 0, master_col: 0, row_cnt: 2, col_cnt: 1, block_id: bid, block_sheet_idx: None,
            }),
        ],
        undoable: false, init: false,
    }));
    let val = |wb: &Workbook| wb.get_sheet_by_idx(0).unwrap().get_value(0, 5).unwrap();
    assert!(matches!(val(&wb), Value::Number(n) if (n - 30.0).abs() < 1e-9),
        "baseline SUM = 30, got {:?}", val(&wb));

    // Append a 3rd row at the TAIL (start == row_cnt) and fill it with 7.
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![
            EditPayload::InsertRowsInBlock(InsertRowsInBlock {
                sheet_idx: 0, block_id: bid, start: 2, cnt: 1,
            }),
            EditPayload::CellInput(CellInput { sheet_idx: 0, row: 2, col: 3, content: "7".into() }),
        ],
        undoable: false, init: false,
    }));
    assert!(matches!(val(&wb), Value::Number(n) if (n - 37.0).abs() < 1e-9),
        "SUM must follow the tail-appended block row (10+20+7=37), got {:?}", val(&wb));

    // LATER edit of the appended cell (separate txn) must also recompute SUM.
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::CellInput(CellInput {
            sheet_idx: 0, row: 2, col: 3, content: "100".into(),
        })],
        undoable: false, init: false,
    }));
    assert!(matches!(val(&wb), Value::Number(n) if (n - 130.0).abs() < 1e-9),
        "editing the appended cell later must recompute SUM (10+20+100=130), got {:?}", val(&wb));
}

// A linked region is a variable-length RECORD: it may be referenced only one
// WHOLE column at a time. References that touch the region any other way
// (multi-column / whole region / partial height / a single cell) are #VALUE!.
#[test]
fn linked_record_rejects_non_column_references() {
    use crate::controller::display::Value;
    use crate::edit_action::{CellInput, CreateLink};

    // Build A1:B6 block (col A = 10.., col B = 1,3,4,5,6,7) and literal 1..4 in
    // A/B rows 1..4 of a DIFFERENT area we'll link. `formula` is placed at G1,
    // and `formula_first` controls its order vs. CreateLink(D1:E4 -> block).
    // Layout: block at D1:E6; linked source at A1:B4 (2 cols x 4 rows).
    let build = |formula: &str, formula_first: bool| -> Workbook {
        let mut wb = Workbook::default();
        let bid = wb.get_available_block_id(0).unwrap();
        let mut payloads = vec![EditPayload::CreateBlock(CreateBlock {
            sheet_idx: 0, id: bid, master_row: 0, master_col: 3,
            row_cnt: 6, col_cnt: 2, owner: None, modify_policy: None,
        })];
        for (i, v) in [1, 3, 4, 5, 6, 7].iter().enumerate() {
            payloads.push(EditPayload::CellInput(CellInput {
                sheet_idx: 0, row: i, col: 4, content: v.to_string(),
            }));
        }
        for (i, v) in [1, 2, 3, 4].iter().enumerate() {
            payloads.push(EditPayload::CellInput(CellInput {
                sheet_idx: 0, row: i, col: 0, content: (v * 10).to_string(),
            }));
            payloads.push(EditPayload::CellInput(CellInput {
                sheet_idx: 0, row: i, col: 1, content: v.to_string(),
            }));
        }
        let f = EditPayload::CellInput(CellInput {
            sheet_idx: 0, row: 0, col: 6, content: formula.to_string(),
        });
        let link = EditPayload::CreateLink(CreateLink {
            sheet_idx: 0, master_row: 0, master_col: 0, row_cnt: 4, col_cnt: 2, block_id: bid, block_sheet_idx: None,
        });
        let payloads = if formula_first {
            payloads.push(f); payloads.push(link); payloads
        } else {
            payloads.push(link); payloads.push(f); payloads
        };
        wb.handle_action(EditAction::Payloads(PayloadsAction {
            payloads, undoable: false, init: false,
        }));
        wb
    };

    let is_value_err = |wb: &Workbook| -> bool {
        matches!(wb.get_sheet_by_idx(0).unwrap().get_value(0, 6).unwrap(),
                 Value::Error(s) if s == "#VALUE!")
    };
    let num = |wb: &Workbook| -> f64 {
        match wb.get_sheet_by_idx(0).unwrap().get_value(0, 6).unwrap() {
            Value::Number(n) => n,
            other => panic!("expected number, got {other:?}"),
        }
    };

    for first in [true, false] {
        // Valid full column B -> block col E = 26.
        assert!((num(&build("=SUM(B1:B4)", first)) - 26.0).abs() < 1e-9);
        // Whole 2-col region -> #VALUE.
        assert!(is_value_err(&build("=SUM(A1:B4)", first)), "whole region (first={first})");
        // Partial-height single column -> #VALUE.
        assert!(is_value_err(&build("=SUM(A1:A2)", first)), "partial column (first={first})");
        // A single cell inside the region -> #VALUE.
        assert!(is_value_err(&build("=A1+0", first)), "single cell (first={first})");
        // A reference entirely OUTSIDE the region is unaffected (Z1 empty => 0).
        assert!((num(&build("=SUM(Z1:Z9)", first))).abs() < 1e-9);
    }
}

#[test]
fn get_links_reports_linked_source_range_coords() {
    use crate::edit_action::{CellInput, CreateLink};

    let mut wb = Workbook::default();
    let bid = wb.get_available_block_id(0).unwrap();

    // A backing block at D1:D2, and a formula over A1:A2 linked to it.
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![
            EditPayload::CellInput(CellInput { sheet_idx: 0, row: 0, col: 0, content: "1".to_string() }),
            EditPayload::CellInput(CellInput { sheet_idx: 0, row: 1, col: 0, content: "2".to_string() }),
            EditPayload::CreateBlock(CreateBlock {
                sheet_idx: 0, id: bid, master_row: 0, master_col: 3,
                row_cnt: 2, col_cnt: 1, owner: None, modify_policy: None,
            }),
            EditPayload::CreateLink(CreateLink {
                sheet_idx: 0, master_row: 0, master_col: 0, row_cnt: 2, col_cnt: 1, block_id: bid, block_sheet_idx: None,
            }),
        ],
        undoable: false,
        init: false,
    }));

    let ws = wb.get_sheet_by_idx(0).unwrap();
    let links = ws.get_links();
    assert_eq!(links.len(), 1, "exactly one link, got {:?}", links);
    let l = &links[0];
    // The source range A1:A2 -> rows 0..1, col 0, pointing at the block.
    assert_eq!(l.block_id, bid);
    assert_eq!((l.start_row, l.start_col), (0, 0));
    assert_eq!((l.end_row, l.end_col), (1, 0));
    assert_eq!(l.sheet_idx, 0);
}

#[test]
fn test_check_formula() {
    let wb = Workbook::new();
    let r = wb.check_formula("=1+1".to_string());
    assert!(r);

    let r = wb.check_formula("=SUM(1)+".to_string());
    assert!(!r);
}

#[test]
fn create_block_with_owner_and_policy_roundtrip() {
    // Create a workbook with a block carrying an owner and a non-default policy,
    // save to .xlsx bytes, reload, and verify the metadata survives the round trip.
    let mut wb = Workbook::default();
    let id = wb.get_available_block_id(0).unwrap();
    let payload_action = PayloadsAction {
        payloads: vec![EditPayload::CreateBlock(CreateBlock {
            sheet_idx: 0,
            id,
            master_row: 1,
            master_col: 1,
            row_cnt: 2,
            col_cnt: 2,
            owner: Some("what-if-calculator".to_string()),
            modify_policy: Some(ModifyPolicy::OwnerAndUser),
        })],
        undoable: false,
        init: false,
    };
    let _ = wb.handle_action(EditAction::Payloads(payload_action));

    let bytes = wb.save().expect("save");
    let reloaded = Workbook::from_file(&bytes, "roundtrip.xlsx".to_string()).expect("reload");

    let info = reloaded
        .get_block_modify_info(0, id)
        .expect("block missing after reload");
    assert_eq!(info.owner, "what-if-calculator");
    assert!(matches!(info.modify_policy, ModifyPolicy::OwnerAndUser));
}

fn author(name: &str) -> AuthorInput {
    AuthorInput {
        display_name: name.to_string(),
        user_id: None,
        provider_id: None,
    }
}

fn enterprise_author(name: &str, user_id: &str) -> AuthorInput {
    AuthorInput {
        display_name: name.to_string(),
        user_id: Some(user_id.to_string()),
        provider_id: Some("AD".to_string()),
    }
}

#[test]
fn comment_thread_add_reply_mention_edit_delete() {
    let mut wb = Workbook::default();

    // Root comment authored by Alice, mentioning Bob (an enterprise user).
    let root_id = "{root-0000-0000-0000-000000000001}".to_string();
    let bob = enterprise_author("Bob", "bob@corp.com");
    let r = wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::AddComment(AddComment {
            sheet_idx: 0,
            row: 2,
            col: 3,
            comment_id: root_id.clone(),
            parent_id: None,
            author: enterprise_author("Alice", "alice@corp.com"),
            dt: "2026-07-03T10:00:00Z".to_string(),
            content: "Please review @Bob".to_string(),
            mentions: vec![CommentMention {
                start: 15,
                len: 4,
                author: bob.clone(),
                mention_id: None,
            }],
        })],
        undoable: true,
        init: false,
    }));
    assert!(matches!(r.status, crate::edit_action::StatusCode::Ok(_)));

    // Reply authored by Bob.
    let reply_id = "{reply-0000-0000-0000-000000000002}".to_string();
    let _ = wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::AddComment(AddComment {
            sheet_idx: 0,
            row: 2,
            col: 3,
            comment_id: reply_id.clone(),
            parent_id: Some(root_id.clone()),
            author: bob.clone(),
            dt: "2026-07-03T10:05:00Z".to_string(),
            content: "Done".to_string(),
            mentions: vec![],
        })],
        undoable: true,
        init: false,
    }));

    {
        let ws = wb.get_sheet_by_idx(0).unwrap();
        let comment = ws.get_comment(2, 3).expect("comment thread missing");
        assert_eq!(comment.notes.len(), 2);
        let root = &comment.notes[0];
        assert_eq!(root.author.display_name, "Alice");
        assert_eq!(root.author.user_id.as_deref(), Some("alice@corp.com"));
        assert_eq!(root.mentions.len(), 1);
        assert_eq!(root.mentions[0].person.display_name, "Bob");
        assert!(root.parent_id.is_none());
        let reply = &comment.notes[1];
        assert_eq!(reply.author.display_name, "Bob");
        assert_eq!(reply.parent_id.as_deref(), Some(root_id.as_str()));
        // Alice + Bob mentioned/authored, so at least 2 sheet comments? Only one thread.
        assert_eq!(ws.get_comments().len(), 1);
    }

    // Edit the root note's text.
    let _ = wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::EditComment(EditComment {
            sheet_idx: 0,
            comment_id: root_id.clone(),
            content: "Reviewed, thanks".to_string(),
            mentions: vec![],
        })],
        undoable: true,
        init: false,
    }));
    {
        let ws = wb.get_sheet_by_idx(0).unwrap();
        let comment = ws.get_comment(2, 3).unwrap();
        assert_eq!(comment.notes[0].content, "Reviewed, thanks");
        assert_eq!(comment.notes[0].mentions.len(), 0);
    }

    // Resolve the thread.
    let _ = wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::ResolveComment(ResolveComment {
            sheet_idx: 0,
            comment_id: root_id.clone(),
            resolved: true,
        })],
        undoable: true,
        init: false,
    }));
    {
        let ws = wb.get_sheet_by_idx(0).unwrap();
        assert!(ws.get_comment(2, 3).unwrap().notes[0].resolved);
    }

    // Delete the reply only — root should remain.
    let _ = wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::DeleteComment(DeleteComment {
            sheet_idx: 0,
            comment_id: reply_id.clone(),
        })],
        undoable: true,
        init: false,
    }));
    {
        let ws = wb.get_sheet_by_idx(0).unwrap();
        assert_eq!(ws.get_comment(2, 3).unwrap().notes.len(), 1);
    }

    // Deleting the root removes the whole thread.
    let _ = wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![EditPayload::DeleteComment(DeleteComment {
            sheet_idx: 0,
            comment_id: root_id.clone(),
        })],
        undoable: true,
        init: false,
    }));
    {
        let ws = wb.get_sheet_by_idx(0).unwrap();
        assert!(ws.get_comment(2, 3).is_none());
    }
}

#[test]
fn comment_roundtrip_persists_thread_and_persons() {
    let mut wb = Workbook::default();
    let root_id = "{root-0000-0000-0000-0000000000aa}".to_string();
    let reply_id = "{reply-0000-0000-0000-0000000000bb}".to_string();
    let bob = enterprise_author("Bob", "bob@corp.com");

    let _ = wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![
            EditPayload::AddComment(AddComment {
                sheet_idx: 0,
                row: 5,
                col: 1,
                comment_id: root_id.clone(),
                parent_id: None,
                author: author("Guest"),
                dt: "2026-07-03T12:00:00Z".to_string(),
                content: "cc @Bob".to_string(),
                mentions: vec![CommentMention {
                    start: 3,
                    len: 4,
                    author: bob.clone(),
                    mention_id: None,
                }],
            }),
            EditPayload::AddComment(AddComment {
                sheet_idx: 0,
                row: 5,
                col: 1,
                comment_id: reply_id.clone(),
                parent_id: Some(root_id.clone()),
                author: bob.clone(),
                dt: "2026-07-03T12:01:00Z".to_string(),
                content: "ack".to_string(),
                mentions: vec![],
            }),
        ],
        undoable: false,
        init: false,
    }));

    let bytes = wb.save().expect("save");
    let reloaded = Workbook::from_file(&bytes, "comments.xlsx".to_string()).expect("reload");
    let ws = reloaded.get_sheet_by_idx(0).unwrap();
    let comment = ws.get_comment(5, 1).expect("thread lost on reload");
    assert_eq!(comment.notes.len(), 2);
    assert_eq!(comment.notes[0].content, "cc @Bob");
    assert_eq!(comment.notes[0].mentions.len(), 1);
    // The mentioned person's directory identity survived the round trip.
    assert_eq!(
        comment.notes[0].mentions[0].person.user_id.as_deref(),
        Some("bob@corp.com")
    );
    assert_eq!(
        comment.notes[1].parent_id.as_deref(),
        Some(root_id.as_str())
    );
    assert_eq!(comment.notes[1].author.display_name, "Bob");
}

#[test]
fn dependency_tracking_precedents_and_dependents() {
    use super::CellRefRange;
    use crate::edit_action::CellInput;

    // A1=1, A2=2; C1=SUM(A1:A2) (a RANGE reference), C2=A1*2 (a SINGLE-cell ref).
    let mut wb = Workbook::default();
    let cell = |row, col, content: &str| {
        EditPayload::CellInput(CellInput {
            sheet_idx: 0,
            row,
            col,
            content: content.to_string(),
        })
    };
    wb.handle_action(EditAction::Payloads(PayloadsAction {
        payloads: vec![
            cell(0, 0, "1"),
            cell(1, 0, "2"),
            cell(0, 2, "=SUM(A1:A2)"),
            cell(1, 2, "=A1*2"),
        ],
        undoable: false,
        init: false,
    }));
    let ws = wb.get_sheet_by_idx(0).unwrap();

    let is_single = |r: &CellRefRange| {
        !r.all_rows && !r.all_cols && r.start_row == r.end_row && r.start_col == r.end_col
    };

    // Dependents of A1:A2 → C1 (via the A1:A2 range) and C2 (via single A1).
    let deps = ws.get_dependents(0, 0, 1, 0).unwrap();
    let c1 = deps
        .iter()
        .find(|d| d.row == 0 && d.col == 2)
        .expect("C1 must depend on A1:A2");
    assert!(
        !is_single(&c1.via)
            && c1.via.start_row == 0
            && c1.via.end_row == 1
            && c1.via.start_col == 0
            && c1.via.end_col == 0,
        "C1's reference is the multi-cell range A1:A2, got {:?}",
        c1.via
    );
    let c2 = deps
        .iter()
        .find(|d| d.row == 1 && d.col == 2)
        .expect("C2 must depend on A1");
    assert!(is_single(&c2.via), "C2's reference is single-cell A1");

    // Dependents of A2 ALONE → C1 (its range covers A2) but NOT C2 (refs A1).
    let deps_a2 = ws.get_dependents(1, 0, 1, 0).unwrap();
    assert!(
        deps_a2.iter().any(|d| d.row == 0 && d.col == 2),
        "C1 depends on A2 via the range"
    );
    assert!(
        !deps_a2.iter().any(|d| d.row == 1 && d.col == 2),
        "C2 does NOT depend on A2"
    );

    // Precedents of C1 → the A1:A2 range.
    let prec = ws.get_precedents(0, 2).unwrap();
    assert!(
        prec.iter()
            .any(|r| r.start_row == 0 && r.end_row == 1 && r.start_col == 0 && r.end_col == 0),
        "C1's precedent is A1:A2, got {:?}",
        prec
    );
}