mdstore 1.2.0

A file-based storage engine that stores structured data as Markdown files with YAML frontmatter
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
//! Core CRUD operations for config-driven item types.
//!
//! All functions take a `type_dir: &Path` pointing to the directory where
//! items of a given type are stored, working generically across any item type.

use crate::config::{IdStrategy, TypeConfig};
use crate::error::StoreError;
use crate::filters::Filters;
use crate::frontmatter::{extract_frontmatter_comment, generate_frontmatter, parse_frontmatter};
use crate::reconcile::{acquire_display_number_lock, get_next_display_number};
use crate::types::{
    CreateOptions, DuplicateOptions, DuplicateResult, Frontmatter, Item, MoveResult, UpdateOptions,
};
use crate::util::now_iso;
use std::path::Path;
use tokio::fs;

/// Check if a filename is a valid item file (`.md` but not `config.yaml`).
fn is_item_file(name: &str) -> bool {
    std::path::Path::new(name)
        .extension()
        .is_some_and(|ext| ext.eq_ignore_ascii_case("md"))
}

/// Validate status against the config's allowed statuses.
fn validate_status(config: &TypeConfig, status: &str) -> Result<(), StoreError> {
    if !config.features.status {
        return Ok(());
    }
    if config.statuses.is_empty() {
        return Ok(());
    }
    if config
        .statuses
        .iter()
        .any(|s| s.eq_ignore_ascii_case(status))
    {
        Ok(())
    } else {
        Err(StoreError::InvalidStatus {
            status: status.to_string(),
            allowed: config.statuses.clone(),
        })
    }
}

/// Validate priority against the config's priority levels.
fn validate_priority(config: &TypeConfig, priority: u32) -> Result<(), StoreError> {
    if !config.features.priority {
        return Ok(());
    }
    let max = config.priority_levels.unwrap_or(3);
    if priority < 1 || priority > max {
        return Err(StoreError::InvalidPriority { priority, max });
    }
    Ok(())
}

/// Create a new item.
///
/// Generates an ID based on the config's `identifier`, assigns a display number
/// if enabled, validates status/priority, and writes the item file.
pub async fn create(
    type_dir: &Path,
    config: &TypeConfig,
    options: CreateOptions,
) -> Result<Item, StoreError> {
    fs::create_dir_all(type_dir).await?;

    // Generate ID
    let id = match &options.id {
        Some(explicit_id) => explicit_id.clone(),
        None => {
            if config.identifier == IdStrategy::Slug {
                let slug = slug::slugify(&options.title);
                if slug.is_empty() {
                    return Err(StoreError::ValidationError(
                        "Cannot generate slug from empty title".to_string(),
                    ));
                }
                slug
            } else {
                // Default to UUID
                uuid::Uuid::new_v4().to_string()
            }
        }
    };

    // Check for existing item
    let file_path = type_dir.join(format!("{id}.md"));
    if file_path.exists() {
        return Err(StoreError::AlreadyExists(id));
    }

    // Acquire per-directory lock to serialize display number assignment (held until write)
    let _dn_guard;
    let display_number = if config.features.display_number {
        _dn_guard = Some(acquire_display_number_lock(type_dir).await);
        Some(get_next_display_number(type_dir).await?)
    } else {
        _dn_guard = None;
        None
    };

    // Resolve and validate status
    let status = if config.features.status {
        let s = options
            .status
            .or_else(|| config.default_status.clone())
            .unwrap_or_default();
        validate_status(config, &s)?;
        Some(s)
    } else {
        None
    };

    // Resolve and validate priority
    let priority = if config.features.priority {
        let max = config.priority_levels.unwrap_or(3);
        let p = options
            .priority
            .unwrap_or_else(|| crate::validation::priority::default_priority(max));
        validate_priority(config, p)?;
        Some(p)
    } else {
        None
    };

    let now = now_iso();
    let frontmatter = Frontmatter {
        display_number,
        status,
        priority,
        created_at: now.clone(),
        updated_at: now,
        deleted_at: None,
        tags: options.tags,
        projects: options.projects,
        custom_fields: options.custom_fields,
    };

    // Write the item file
    let comment = options.comment.clone();
    let content = generate_frontmatter(
        &frontmatter,
        &options.title,
        &options.body,
        comment.as_deref(),
    );
    fs::write(&file_path, &content).await?;

    Ok(Item {
        id,
        title: options.title,
        body: options.body,
        frontmatter,
        comment,
    })
}

/// Get a single item by ID.
pub async fn get(type_dir: &Path, id: &str) -> Result<Item, StoreError> {
    let file_path = type_dir.join(format!("{id}.md"));

    if !file_path.exists() {
        return Err(StoreError::NotFound(id.to_string()));
    }

    let content = fs::read_to_string(&file_path).await?;
    let comment = extract_frontmatter_comment(&content);
    let (frontmatter, title, body) = parse_frontmatter::<Frontmatter>(&content)
        .map_err(|e| StoreError::Custom(format!("Frontmatter error: {e}")))?;

    Ok(Item {
        id: id.to_string(),
        title,
        body,
        frontmatter,
        comment,
    })
}

/// List items with optional filters.
pub async fn list(type_dir: &Path, filters: Filters) -> Result<Vec<Item>, StoreError> {
    if !type_dir.exists() {
        return Ok(Vec::new());
    }

    let mut items = Vec::new();
    let mut entries = fs::read_dir(type_dir).await?;

    while let Some(entry) = entries.next_entry().await? {
        if !entry.file_type().await?.is_file() {
            continue;
        }

        let name = match entry.file_name().to_str() {
            Some(n) => n.to_string(),
            None => continue,
        };

        if !is_item_file(&name) {
            continue;
        }

        let id = name.trim_end_matches(".md").to_string();
        let content = match fs::read_to_string(entry.path()).await {
            Ok(c) => c,
            Err(e) => {
                tracing::warn!(path = %entry.path().display(), error = %e, "skipping file: read error");
                continue;
            }
        };

        let comment = extract_frontmatter_comment(&content);
        let (frontmatter, title, body) = match parse_frontmatter::<Frontmatter>(&content) {
            Ok(result) => result,
            Err(e) => {
                tracing::warn!(path = %entry.path().display(), error = %e, "skipping file: malformed frontmatter");
                continue;
            }
        };

        items.push(Item {
            id,
            title,
            body,
            frontmatter,
            comment,
        });
    }

    // Apply filters
    let items = apply_filters(items, &filters);

    Ok(items)
}

/// Apply filters to a list of items.
fn apply_filters(mut items: Vec<Item>, filters: &Filters) -> Vec<Item> {
    // Filter out soft-deleted unless include_deleted
    if !filters.include_deleted {
        items.retain(|item| item.frontmatter.deleted_at.is_none());
    }

    // Filter by statuses (any match)
    if let Some(ref status_filters) = filters.statuses {
        items.retain(|item| {
            item.frontmatter
                .status
                .as_ref()
                .is_some_and(|s| status_filters.iter().any(|f| f.eq_ignore_ascii_case(s)))
        });
    }

    // Filter by exact priority
    if let Some(priority_filter) = filters.priority {
        items.retain(|item| item.frontmatter.priority == Some(priority_filter));
    }

    // Filter by priority range
    if let Some(lte) = filters.priority_lte {
        items.retain(|item| item.frontmatter.priority.is_some_and(|p| p <= lte));
    }
    if let Some(gte) = filters.priority_gte {
        items.retain(|item| item.frontmatter.priority.is_some_and(|p| p >= gte));
    }

    // Filter by tags — item must have at least one of the given tags
    if let Some(ref any_tags) = filters.tags_any {
        items.retain(|item| {
            let item_tags = item.frontmatter.tags.as_deref().unwrap_or(&[]);
            any_tags.iter().any(|t| item_tags.contains(t))
        });
    }

    // Filter by tags — item must have all of the given tags
    if let Some(ref all_tags) = filters.tags_all {
        items.retain(|item| {
            let item_tags = item.frontmatter.tags.as_deref().unwrap_or(&[]);
            all_tags.iter().all(|t| item_tags.contains(t))
        });
    }

    // Sort by display_number (if present), then by created_at
    items.sort_by(
        |a, b| match (a.frontmatter.display_number, b.frontmatter.display_number) {
            (Some(an), Some(bn)) => an.cmp(&bn),
            (Some(_), None) => std::cmp::Ordering::Less,
            (None, Some(_)) => std::cmp::Ordering::Greater,
            (None, None) => a.frontmatter.created_at.cmp(&b.frontmatter.created_at),
        },
    );

    // Apply offset
    if let Some(offset) = filters.offset {
        if offset < items.len() {
            items = items.split_off(offset);
        } else {
            items.clear();
        }
    }

    // Apply limit
    if let Some(limit) = filters.limit {
        items.truncate(limit);
    }

    items
}

/// Update an existing item.
pub async fn update(
    type_dir: &Path,
    config: &TypeConfig,
    id: &str,
    options: UpdateOptions,
) -> Result<Item, StoreError> {
    let file_path = type_dir.join(format!("{id}.md"));

    if !file_path.exists() {
        return Err(StoreError::NotFound(id.to_string()));
    }

    let content = fs::read_to_string(&file_path).await?;
    let existing_comment = extract_frontmatter_comment(&content);
    let (mut frontmatter, current_title, current_body) = parse_frontmatter::<Frontmatter>(&content)
        .map_err(|e| StoreError::Custom(format!("Frontmatter error: {e}")))?;

    // Check if item is soft-deleted
    if frontmatter.deleted_at.is_some() {
        return Err(StoreError::IsDeleted(id.to_string()));
    }

    // Update status if provided
    if let Some(ref new_status) = options.status {
        validate_status(config, new_status)?;
        frontmatter.status = Some(new_status.clone());
    }

    // Update priority if provided
    if let Some(new_priority) = options.priority {
        validate_priority(config, new_priority)?;
        frontmatter.priority = Some(new_priority);
    }

    // Update tags if provided
    if let Some(new_tags) = options.tags {
        frontmatter.tags = if new_tags.is_empty() {
            None
        } else {
            Some(new_tags)
        };
    }

    // Update projects if provided
    if let Some(new_projects) = options.projects {
        frontmatter.projects = if new_projects.is_empty() {
            None
        } else {
            Some(new_projects)
        };
    }

    // Merge custom fields
    for (key, value) in &options.custom_fields {
        frontmatter.custom_fields.insert(key.clone(), value.clone());
    }

    frontmatter.updated_at = now_iso();

    let title = options.title.unwrap_or(current_title);
    let body = options.body.unwrap_or(current_body);

    // Resolve comment: explicit update overrides existing; None preserves existing
    let comment = match options.comment {
        Some(c) if c.is_empty() => None,
        Some(c) => Some(c),
        None => existing_comment,
    };

    // Write updated file
    let new_content = generate_frontmatter(&frontmatter, &title, &body, comment.as_deref());
    fs::write(&file_path, &new_content).await?;

    Ok(Item {
        id: id.to_string(),
        title,
        body,
        frontmatter,
        comment,
    })
}

/// Delete an item (hard delete).
///
/// If the item is not yet soft-deleted and `force` is false, this performs a
/// soft delete instead. If the item is already soft-deleted (or `force` is
/// true), this removes the file permanently.
pub async fn delete(type_dir: &Path, id: &str, force: bool) -> Result<(), StoreError> {
    let file_path = type_dir.join(format!("{id}.md"));

    if !file_path.exists() {
        return Err(StoreError::NotFound(id.to_string()));
    }

    // If not forcing, soft-delete instead
    if !force {
        // Check if already soft-deleted; if so, hard delete
        let content = fs::read_to_string(&file_path).await?;
        let (frontmatter, _, _) = parse_frontmatter::<Frontmatter>(&content)
            .map_err(|e| StoreError::Custom(format!("Frontmatter error: {e}")))?;

        if frontmatter.deleted_at.is_none() {
            // Soft delete instead
            return soft_delete(type_dir, id).await;
        }
    }

    // Hard delete: remove the file
    fs::remove_file(&file_path).await?;

    Ok(())
}

/// Soft-delete an item by setting the `deleted_at` timestamp.
pub async fn soft_delete(type_dir: &Path, id: &str) -> Result<(), StoreError> {
    let file_path = type_dir.join(format!("{id}.md"));

    if !file_path.exists() {
        return Err(StoreError::NotFound(id.to_string()));
    }

    let content = fs::read_to_string(&file_path).await?;
    let comment = extract_frontmatter_comment(&content);
    let (mut frontmatter, title, body) = parse_frontmatter::<Frontmatter>(&content)
        .map_err(|e| StoreError::Custom(format!("Frontmatter error: {e}")))?;

    if frontmatter.deleted_at.is_some() {
        return Err(StoreError::IsDeleted(id.to_string()));
    }

    let now = now_iso();
    frontmatter.deleted_at = Some(now.clone());
    frontmatter.updated_at = now;

    let new_content = generate_frontmatter(&frontmatter, &title, &body, comment.as_deref());
    fs::write(&file_path, &new_content).await?;

    Ok(())
}

/// Restore a soft-deleted item by clearing the `deleted_at` timestamp.
pub async fn restore(type_dir: &Path, id: &str) -> Result<(), StoreError> {
    let file_path = type_dir.join(format!("{id}.md"));

    if !file_path.exists() {
        return Err(StoreError::NotFound(id.to_string()));
    }

    let content = fs::read_to_string(&file_path).await?;
    let comment = extract_frontmatter_comment(&content);
    let (mut frontmatter, title, body) = parse_frontmatter::<Frontmatter>(&content)
        .map_err(|e| StoreError::Custom(format!("Frontmatter error: {e}")))?;

    if frontmatter.deleted_at.is_none() {
        return Err(StoreError::Custom(format!("Item '{id}' is not deleted")));
    }

    frontmatter.deleted_at = None;
    frontmatter.updated_at = now_iso();

    let new_content = generate_frontmatter(&frontmatter, &title, &body, comment.as_deref());
    fs::write(&file_path, &new_content).await?;

    Ok(())
}

/// Duplicate an item to the same or different directory.
///
/// Creates a copy of the item with a new ID and fresh timestamps.
/// For UUID-identified types, a new UUID is generated.
/// For slug-identified types, the default new ID is `"{id}-copy"`.
pub async fn duplicate(
    config: &TypeConfig,
    options: DuplicateOptions,
) -> Result<DuplicateResult, StoreError> {
    // Check duplicate feature is enabled
    if !config.features.duplicate {
        return Err(StoreError::FeatureNotEnabled(format!(
            "duplicate is not enabled for {}",
            config.name
        )));
    }

    // Read source item
    let source_item = get(&options.source_dir, &options.item_id).await?;

    // Generate new ID
    let new_id = match options.new_id {
        Some(ref id) if !id.is_empty() => {
            if config.identifier == IdStrategy::Slug {
                slug::slugify(id)
            } else {
                id.clone()
            }
        }
        _ => {
            if config.identifier == IdStrategy::Slug {
                format!("{}-copy", options.item_id)
            } else {
                uuid::Uuid::new_v4().to_string()
            }
        }
    };

    // Check for existing item in target
    fs::create_dir_all(&options.target_dir).await?;
    let target_file = options.target_dir.join(format!("{new_id}.md"));
    if target_file.exists() {
        return Err(StoreError::AlreadyExists(new_id));
    }

    // Validate status/priority against config
    if let Some(ref status) = source_item.frontmatter.status {
        validate_status(config, status)?;
    }
    if let Some(priority) = source_item.frontmatter.priority {
        validate_priority(config, priority)?;
    }

    // Acquire per-directory lock to serialize display number assignment (held until write)
    let _dn_guard;
    let display_number = if config.features.display_number {
        _dn_guard = Some(acquire_display_number_lock(&options.target_dir).await);
        Some(get_next_display_number(&options.target_dir).await?)
    } else {
        _dn_guard = None;
        None
    };

    // Prepare title
    let new_title = options
        .new_title
        .unwrap_or_else(|| format!("Copy of {}", source_item.title));

    // Create new frontmatter with fresh timestamps
    let now = now_iso();
    let frontmatter = Frontmatter {
        display_number,
        status: source_item.frontmatter.status.clone(),
        priority: source_item.frontmatter.priority,
        created_at: now.clone(),
        updated_at: now,
        deleted_at: None,
        tags: source_item.frontmatter.tags.clone(),
        projects: source_item.frontmatter.projects.clone(),
        custom_fields: source_item.frontmatter.custom_fields.clone(),
    };

    // Write new item file (preserve comment from source)
    let comment = source_item.comment.clone();
    let content = generate_frontmatter(
        &frontmatter,
        &new_title,
        &source_item.body,
        comment.as_deref(),
    );
    fs::write(&target_file, &content).await?;

    Ok(DuplicateResult {
        item: Item {
            id: new_id,
            title: new_title,
            body: source_item.body,
            frontmatter,
            comment,
        },
        original_id: options.item_id,
    })
}

/// Move an item from one directory to another.
///
/// Custom and unknown fields are preserved via the `custom_fields` flatten map
/// on `Frontmatter`, so no raw YAML manipulation is needed.
pub async fn move_item(
    source_dir: &Path,
    target_dir: &Path,
    source_config: &TypeConfig,
    target_config: &TypeConfig,
    item_id: &str,
    new_id: Option<&str>,
) -> Result<MoveResult, StoreError> {
    // 1. Check move feature is enabled on both source and target
    if !source_config.features.move_item {
        return Err(StoreError::FeatureNotEnabled(format!(
            "move is not enabled for {}",
            source_config.name
        )));
    }
    if !target_config.features.move_item {
        return Err(StoreError::FeatureNotEnabled(format!(
            "move is not enabled for {}",
            target_config.name
        )));
    }

    // 2. Same-location check
    let source_canonical =
        std::fs::canonicalize(source_dir).unwrap_or_else(|_| source_dir.to_path_buf());
    let target_canonical =
        std::fs::canonicalize(target_dir).unwrap_or_else(|_| target_dir.to_path_buf());
    if source_canonical == target_canonical {
        return Err(StoreError::SameLocation);
    }

    // 3. Read source file
    let source_file = source_dir.join(format!("{item_id}.md"));
    if !source_file.exists() {
        return Err(StoreError::NotFound(item_id.to_string()));
    }
    let content = fs::read_to_string(&source_file).await?;
    let comment = extract_frontmatter_comment(&content);

    // Parse as Frontmatter — captures all fields (including unknown ones via custom_fields flatten)
    let (mut frontmatter, title, body) = parse_frontmatter::<Frontmatter>(&content)
        .map_err(|e| StoreError::FrontmatterError(e.to_string()))?;

    // 4. Validate status against target config
    if target_config.features.status {
        if let Some(ref status) = frontmatter.status {
            validate_status(target_config, status)?;
        }
    }

    // 5. Validate priority against target config
    if target_config.features.priority {
        if let Some(priority) = frontmatter.priority {
            validate_priority(target_config, priority)?;
        }
    }

    // 6. Determine target ID
    let target_id = if source_config.identifier == IdStrategy::Slug {
        new_id.unwrap_or(item_id).to_string()
    } else {
        // UUID-based: keep the same ID
        item_id.to_string()
    };

    // 7. Check target doesn't already exist
    fs::create_dir_all(target_dir).await?;
    let target_file = target_dir.join(format!("{target_id}.md"));
    if target_file.exists() {
        return Err(StoreError::AlreadyExists(target_id));
    }

    // 8. If display_number feature: acquire lock and assign next display number.
    // Lock held through write (step 9) to prevent concurrent duplicate assignment.
    let _dn_guard = if target_config.features.display_number {
        let guard = acquire_display_number_lock(target_dir).await;
        frontmatter.display_number = Some(get_next_display_number(target_dir).await?);
        Some(guard)
    } else {
        None
    };

    // 9. Update timestamp and write to target (preserve comment from source)
    frontmatter.updated_at = now_iso();
    let new_content = generate_frontmatter(&frontmatter, &title, &body, comment.as_deref());
    fs::write(&target_file, &new_content).await?;

    // 10. Delete source file
    fs::remove_file(&source_file).await?;

    Ok(MoveResult {
        item: Item {
            id: target_id,
            title,
            body,
            frontmatter,
            comment,
        },
        old_id: item_id.to_string(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::TypeFeatures;
    use std::collections::HashMap;

    fn issue_config() -> TypeConfig {
        TypeConfig {
            name: "Issue".to_string(),

            identifier: IdStrategy::Uuid,
            features: TypeFeatures {
                display_number: true,
                status: true,
                priority: true,
                assets: false,
                org_sync: false,
                move_item: true,
                duplicate: true,
            },
            statuses: vec![
                "open".to_string(),
                "planning".to_string(),
                "in-progress".to_string(),
                "closed".to_string(),
            ],
            default_status: Some("open".to_string()),
            priority_levels: Some(3),
            custom_fields: Vec::new(),
        }
    }

    fn minimal_config() -> TypeConfig {
        TypeConfig {
            name: "Note".to_string(),

            identifier: IdStrategy::Uuid,
            features: TypeFeatures::default(),
            statuses: Vec::new(),
            default_status: None,
            priority_levels: None,
            custom_fields: Vec::new(),
        }
    }

    #[tokio::test]
    async fn test_create_and_get() {
        let temp = tempfile::tempdir().unwrap();
        let type_dir = temp.path().join("issues");

        let config = issue_config();
        let options = CreateOptions {
            title: "Test Issue".to_string(),
            body: "This is a test.".to_string(),
            id: None,
            status: Some("open".to_string()),
            priority: Some(2),
            tags: None,
            projects: None,
            custom_fields: HashMap::new(),
            comment: None,
        };

        let created = create(&type_dir, &config, options).await.unwrap();
        assert_eq!(created.title, "Test Issue");
        assert_eq!(created.body, "This is a test.");
        assert_eq!(created.frontmatter.display_number, Some(1));
        assert_eq!(created.frontmatter.status, Some("open".to_string()));
        assert_eq!(created.frontmatter.priority, Some(2));

        // Get it back
        let fetched = get(&type_dir, &created.id).await.unwrap();
        assert_eq!(fetched.title, "Test Issue");
        assert_eq!(fetched.frontmatter.display_number, Some(1));
    }

    #[tokio::test]
    async fn test_create_minimal_features() {
        let temp = tempfile::tempdir().unwrap();
        let type_dir = temp.path().join("notes");

        let config = minimal_config();
        let options = CreateOptions {
            title: "Simple Note".to_string(),
            body: "Just a note.".to_string(),
            id: None,
            status: None,
            priority: None,
            tags: None,
            projects: None,
            custom_fields: HashMap::new(),
            comment: None,
        };

        let created = create(&type_dir, &config, options).await.unwrap();
        assert!(created.frontmatter.display_number.is_none());
        assert!(created.frontmatter.status.is_none());
        assert!(created.frontmatter.priority.is_none());
    }

    #[tokio::test]
    async fn test_create_slug_id_strategy() {
        let temp = tempfile::tempdir().unwrap();
        let type_dir = temp.path().join("docs");

        let mut config = minimal_config();
        config.identifier = IdStrategy::Slug;

        let options = CreateOptions {
            title: "Getting Started Guide".to_string(),
            body: "Welcome!".to_string(),
            id: None,
            status: None,
            priority: None,
            tags: None,
            projects: None,
            custom_fields: HashMap::new(),
            comment: None,
        };

        let created = create(&type_dir, &config, options).await.unwrap();
        assert_eq!(created.id, "getting-started-guide");
    }

    #[tokio::test]
    async fn test_create_invalid_status() {
        let temp = tempfile::tempdir().unwrap();
        let type_dir = temp.path().join("issues");

        let config = issue_config();
        let options = CreateOptions {
            title: "Bad Status".to_string(),
            body: String::new(),
            id: None,
            status: Some("nonexistent".to_string()),
            priority: None,
            tags: None,
            projects: None,
            custom_fields: HashMap::new(),
            comment: None,
        };

        let result = create(&type_dir, &config, options).await;
        assert!(result.is_err());
        assert!(matches!(result, Err(StoreError::InvalidStatus { .. })));
    }

    #[tokio::test]
    async fn test_create_invalid_priority() {
        let temp = tempfile::tempdir().unwrap();
        let type_dir = temp.path().join("issues");

        let config = issue_config();
        let options = CreateOptions {
            title: "Bad Priority".to_string(),
            body: String::new(),
            id: None,
            status: Some("open".to_string()),
            priority: Some(99),
            tags: None,
            projects: None,
            custom_fields: HashMap::new(),
            comment: None,
        };

        let result = create(&type_dir, &config, options).await;
        assert!(result.is_err());
        assert!(matches!(result, Err(StoreError::InvalidPriority { .. })));
    }

    #[tokio::test]
    async fn test_list_with_filters() {
        let temp = tempfile::tempdir().unwrap();
        let type_dir = temp.path().join("issues");

        let config = issue_config();

        // Create multiple items
        for (title, status) in [
            ("Open 1", "open"),
            ("Open 2", "open"),
            ("Closed 1", "closed"),
        ] {
            let options = CreateOptions {
                title: title.to_string(),
                body: String::new(),
                id: None,
                status: Some(status.to_string()),
                priority: Some(2),
                tags: None,
                projects: None,
                custom_fields: HashMap::new(),
                comment: None,
            };
            create(&type_dir, &config, options).await.unwrap();
        }

        // List all
        let all = list(&type_dir, Filters::default()).await.unwrap();
        assert_eq!(all.len(), 3);

        // List open only
        let open = list(&type_dir, Filters::new().with_status("open"))
            .await
            .unwrap();
        assert_eq!(open.len(), 2);

        // List with limit
        let limited = list(&type_dir, Filters::new().with_limit(1)).await.unwrap();
        assert_eq!(limited.len(), 1);

        // List with offset
        let offset = list(&type_dir, Filters::new().with_offset(2))
            .await
            .unwrap();
        assert_eq!(offset.len(), 1);
    }

    #[tokio::test]
    async fn test_update() {
        let temp = tempfile::tempdir().unwrap();
        let type_dir = temp.path().join("issues");

        let config = issue_config();
        let options = CreateOptions {
            title: "Original Title".to_string(),
            body: "Original body.".to_string(),
            id: None,
            status: Some("open".to_string()),
            priority: Some(2),
            tags: None,
            projects: None,
            custom_fields: HashMap::new(),
            comment: None,
        };

        let created = create(&type_dir, &config, options).await.unwrap();

        let update_options = UpdateOptions {
            title: Some("Updated Title".to_string()),
            body: Some("Updated body.".to_string()),
            status: Some("closed".to_string()),
            priority: Some(1),
            tags: None,
            projects: None,
            custom_fields: HashMap::from([("env".to_string(), serde_json::json!("prod"))]),
            comment: None,
        };

        let updated = update(&type_dir, &config, &created.id, update_options)
            .await
            .unwrap();

        assert_eq!(updated.title, "Updated Title");
        assert_eq!(updated.body, "Updated body.");
        assert_eq!(updated.frontmatter.status, Some("closed".to_string()));
        assert_eq!(updated.frontmatter.priority, Some(1));
        assert_eq!(
            updated.frontmatter.custom_fields.get("env"),
            Some(&serde_json::json!("prod"))
        );
    }

    #[tokio::test]
    async fn test_update_not_found() {
        let temp = tempfile::tempdir().unwrap();
        let type_dir = temp.path().join("issues");
        fs::create_dir_all(&type_dir).await.unwrap();

        let config = issue_config();
        let result = update(&type_dir, &config, "nonexistent", UpdateOptions::default()).await;
        assert!(result.is_err());
        assert!(matches!(result, Err(StoreError::NotFound(_))));
    }

    #[tokio::test]
    async fn test_soft_delete_and_restore() {
        let temp = tempfile::tempdir().unwrap();
        let type_dir = temp.path().join("issues");

        let config = issue_config();
        let options = CreateOptions {
            title: "To Delete".to_string(),
            body: String::new(),
            id: None,
            status: Some("open".to_string()),
            priority: Some(2),
            tags: None,
            projects: None,
            custom_fields: HashMap::new(),
            comment: None,
        };

        let created = create(&type_dir, &config, options).await.unwrap();

        // Soft delete
        soft_delete(&type_dir, &created.id).await.unwrap();

        // Should not appear in default list
        let items = list(&type_dir, Filters::default()).await.unwrap();
        assert!(items.is_empty());

        // Should appear with include_deleted
        let items = list(&type_dir, Filters::new().include_deleted())
            .await
            .unwrap();
        assert_eq!(items.len(), 1);
        assert!(items.first().unwrap().frontmatter.deleted_at.is_some());

        // Restore
        restore(&type_dir, &created.id).await.unwrap();

        // Should appear again
        let items = list(&type_dir, Filters::default()).await.unwrap();
        assert_eq!(items.len(), 1);
        assert!(items.first().unwrap().frontmatter.deleted_at.is_none());
    }

    #[tokio::test]
    async fn test_soft_delete_timestamps_are_identical() {
        let temp = tempfile::tempdir().unwrap();
        let type_dir = temp.path().join("issues");

        let config = issue_config();
        let options = CreateOptions {
            title: "Timestamp Test".to_string(),
            body: String::new(),
            id: None,
            status: Some("open".to_string()),
            priority: Some(2),
            tags: None,
            projects: None,
            custom_fields: HashMap::new(),
            comment: None,
        };

        let created = create(&type_dir, &config, options).await.unwrap();
        soft_delete(&type_dir, &created.id).await.unwrap();

        let items = list(&type_dir, Filters::new().include_deleted())
            .await
            .unwrap();
        let item = items.first().unwrap();
        assert_eq!(
            item.frontmatter.deleted_at,
            Some(item.frontmatter.updated_at.clone()),
            "deleted_at and updated_at must be identical after soft_delete"
        );
    }

    #[tokio::test]
    async fn test_hard_delete() {
        let temp = tempfile::tempdir().unwrap();
        let type_dir = temp.path().join("issues");

        let config = issue_config();
        let options = CreateOptions {
            title: "To Hard Delete".to_string(),
            body: String::new(),
            id: None,
            status: Some("open".to_string()),
            priority: Some(2),
            tags: None,
            projects: None,
            custom_fields: HashMap::new(),
            comment: None,
        };

        let created = create(&type_dir, &config, options).await.unwrap();

        // Force hard delete
        delete(&type_dir, &created.id, true).await.unwrap();

        // Should not exist at all
        let result = get(&type_dir, &created.id).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_display_number_auto_increment() {
        let temp = tempfile::tempdir().unwrap();
        let type_dir = temp.path().join("issues");

        let config = issue_config();

        for i in 1..=3u32 {
            let options = CreateOptions {
                title: format!("Issue {i}"),
                body: String::new(),
                id: None,
                status: Some("open".to_string()),
                priority: Some(2),
                tags: None,
                projects: None,
                custom_fields: HashMap::new(),
                comment: None,
            };

            let created = create(&type_dir, &config, options).await.unwrap();
            assert_eq!(created.frontmatter.display_number, Some(i));
        }
    }

    #[tokio::test]
    async fn test_concurrent_create_unique_display_numbers() {
        let temp = tempfile::tempdir().unwrap();
        let type_dir = temp.path().join("issues");

        let config = std::sync::Arc::new(issue_config());

        // Spawn 10 concurrent creates and collect their display numbers
        let handles: Vec<_> = (0..10)
            .map(|i| {
                let dir = type_dir.clone();
                let cfg = std::sync::Arc::clone(&config);
                tokio::spawn(async move {
                    let options = CreateOptions {
                        title: format!("Concurrent Issue {i}"),
                        body: String::new(),
                        id: None,
                        status: Some("open".to_string()),
                        priority: Some(2),
                        tags: None,
                        projects: None,
                        custom_fields: HashMap::new(),
                        comment: None,
                    };
                    create(&dir, &cfg, options).await.unwrap()
                })
            })
            .collect();

        let mut display_numbers: Vec<u32> = Vec::new();
        for handle in handles {
            let item = handle.await.unwrap();
            display_numbers.push(item.frontmatter.display_number.unwrap());
        }

        display_numbers.sort_unstable();
        assert_eq!(display_numbers, (1..=10).collect::<Vec<u32>>());
    }

    #[tokio::test]
    async fn test_update_preserves_fields() {
        let temp = tempfile::tempdir().unwrap();
        let type_dir = temp.path().join("issues");

        let config = issue_config();
        let options = CreateOptions {
            title: "Keep Fields".to_string(),
            body: "Original body.".to_string(),
            id: None,
            status: Some("open".to_string()),
            priority: Some(1),
            tags: None,
            projects: None,
            custom_fields: HashMap::from([("key".to_string(), serde_json::json!("value"))]),
            comment: None,
        };

        let created = create(&type_dir, &config, options).await.unwrap();

        // Update only the title
        let updated = update(
            &type_dir,
            &config,
            &created.id,
            UpdateOptions {
                title: Some("New Title".to_string()),
                ..Default::default()
            },
        )
        .await
        .unwrap();

        assert_eq!(updated.title, "New Title");
        assert_eq!(updated.body, "Original body.");
        assert_eq!(updated.frontmatter.status, Some("open".to_string()));
        assert_eq!(updated.frontmatter.priority, Some(1));
        assert_eq!(
            updated.frontmatter.custom_fields.get("key"),
            Some(&serde_json::json!("value"))
        );
    }

    #[tokio::test]
    async fn test_cannot_update_deleted_item() {
        let temp = tempfile::tempdir().unwrap();
        let type_dir = temp.path().join("issues");

        let config = issue_config();
        let options = CreateOptions {
            title: "Will Delete".to_string(),
            body: String::new(),
            id: None,
            status: Some("open".to_string()),
            priority: Some(2),
            tags: None,
            projects: None,
            custom_fields: HashMap::new(),
            comment: None,
        };

        let created = create(&type_dir, &config, options).await.unwrap();
        soft_delete(&type_dir, &created.id).await.unwrap();

        let result = update(
            &type_dir,
            &config,
            &created.id,
            UpdateOptions {
                title: Some("Fail".to_string()),
                ..Default::default()
            },
        )
        .await;
        assert!(result.is_err());
        assert!(matches!(result, Err(StoreError::IsDeleted(_))));
    }

    #[tokio::test]
    async fn test_already_exists() {
        let temp = tempfile::tempdir().unwrap();
        let type_dir = temp.path().join("notes");

        let mut config = minimal_config();
        config.identifier = IdStrategy::Slug;

        let options = CreateOptions {
            title: "Same Title".to_string(),
            body: String::new(),
            id: None,
            status: None,
            priority: None,
            tags: None,
            projects: None,
            custom_fields: HashMap::new(),
            comment: None,
        };

        create(&type_dir, &config, options.clone()).await.unwrap();

        let result = create(&type_dir, &config, options).await;
        assert!(result.is_err());
        assert!(matches!(result, Err(StoreError::AlreadyExists(_))));
    }

    #[tokio::test]
    async fn test_get_not_found() {
        let temp = tempfile::tempdir().unwrap();
        let type_dir = temp.path().join("issues");
        fs::create_dir_all(&type_dir).await.unwrap();

        let result = get(&type_dir, "nonexistent").await;
        assert!(result.is_err());
        assert!(matches!(result, Err(StoreError::NotFound(_))));
    }

    #[tokio::test]
    async fn test_list_empty() {
        let temp = tempfile::tempdir().unwrap();
        let type_dir = temp.path().join("issues");

        let items = list(&type_dir, Filters::default()).await.unwrap();
        assert!(items.is_empty());
    }

    #[tokio::test]
    async fn test_move_item_target_move_disabled_is_rejected() {
        let temp = tempfile::tempdir().unwrap();
        let source_dir = temp.path().join("issues");
        let target_dir = temp.path().join("notes");

        let source_config = issue_config(); // move_item: true
        let mut target_config = issue_config();
        target_config.features.move_item = false;

        let options = CreateOptions {
            title: "To Move".to_string(),
            body: String::new(),
            id: None,
            status: Some("open".to_string()),
            priority: Some(1),
            tags: None,
            projects: None,
            custom_fields: HashMap::new(),
            comment: None,
        };
        let created = create(&source_dir, &source_config, options).await.unwrap();

        let result = move_item(
            &source_dir,
            &target_dir,
            &source_config,
            &target_config,
            &created.id,
            None,
        )
        .await;

        assert!(matches!(result, Err(StoreError::FeatureNotEnabled(_))));
    }

    #[tokio::test]
    async fn test_duplicate_feature_disabled_returns_error() {
        let temp = tempfile::tempdir().unwrap();
        let type_dir = temp.path().join("issues");

        let mut config = issue_config();
        config.features.duplicate = false;

        let options = CreateOptions {
            title: "Original".to_string(),
            body: String::new(),
            id: None,
            status: Some("open".to_string()),
            priority: Some(2),
            tags: None,
            projects: None,
            custom_fields: HashMap::new(),
            comment: None,
        };
        let created = create(&type_dir, &config, options).await.unwrap();

        let dup_options = DuplicateOptions {
            source_dir: type_dir.clone(),
            target_dir: type_dir.clone(),
            item_id: created.id,
            new_id: None,
            new_title: None,
        };
        let result = duplicate(&config, dup_options).await;
        assert!(result.is_err());
        assert!(matches!(result, Err(StoreError::FeatureNotEnabled(_))));
    }

    #[tokio::test]
    async fn test_move_item_preserves_custom_fields() {
        let temp = tempfile::tempdir().unwrap();
        let source_dir = temp.path().join("source");
        let target_dir = temp.path().join("target");

        let config = issue_config();
        let options = CreateOptions {
            title: "With Custom Fields".to_string(),
            body: "body".to_string(),
            id: None,
            status: Some("open".to_string()),
            priority: Some(1),
            tags: None,
            projects: None,
            custom_fields: HashMap::from([
                ("draft".to_string(), serde_json::json!(true)),
                ("env".to_string(), serde_json::json!("staging")),
            ]),
            comment: None,
        };
        let created = create(&source_dir, &config, options).await.unwrap();

        let result = move_item(
            &source_dir,
            &target_dir,
            &config,
            &config,
            &created.id,
            None,
        )
        .await
        .unwrap();

        assert_eq!(
            result.item.frontmatter.custom_fields.get("draft"),
            Some(&serde_json::json!(true))
        );
        assert_eq!(
            result.item.frontmatter.custom_fields.get("env"),
            Some(&serde_json::json!("staging"))
        );
        // Source file should be gone
        assert!(!source_dir.join(format!("{}.md", created.id)).exists());
    }
}