this-rs 0.0.9

Framework for building complex multi-entity REST and GraphQL APIs with many relationships
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
//! Neo4j storage backend using the neo4rs Bolt protocol driver.
//!
//! Provides `Neo4jDataService<T>` and `Neo4jLinkService` implementations
//! backed by a Neo4j database via `neo4rs::Graph`.
//!
//! # Feature flag
//!
//! This module is gated behind the `neo4j` feature flag:
//! ```toml
//! [dependencies]
//! this-rs = { version = "0.0.7", features = ["neo4j"] }
//! ```
//!
//! # Storage model
//!
//! Entities are stored as Neo4j nodes. Each entity type gets its own label
//! (from `T::resource_name_singular()`). All scalar fields are stored as
//! individual node properties for searchability. A `__data` property holds
//! the full JSON string for reliable deserialization.
//!
//! Links are stored as nodes with label `_Link` (not as native relationships)
//! to maintain compatibility with the `LinkService` contract — which allows
//! creating links without requiring source/target entities to exist in the store.

use crate::core::link::LinkEntity;
use crate::core::{Data, DataService, LinkService};
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use neo4rs::{BoltMap, BoltString, BoltType, Graph, Node, query};
use serde::Serialize;
use serde::de::DeserializeOwned;
use uuid::Uuid;

// ---------------------------------------------------------------------------
// Conversion helpers: JSON ↔ Neo4j properties
// ---------------------------------------------------------------------------

/// Convert a serde_json::Value into a BoltType for Neo4j storage.
///
/// - Strings → BoltType::String
/// - Integers → BoltType::Integer
/// - Floats → BoltType::Float
/// - Booleans → BoltType::Boolean
/// - Null → BoltType::Null
/// - Objects/Arrays → BoltType::String (JSON serialized)
fn json_value_to_bolt(value: &serde_json::Value) -> BoltType {
    match value {
        serde_json::Value::String(s) => BoltType::from(s.clone()),
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                BoltType::from(i)
            } else if let Some(f) = n.as_f64() {
                BoltType::from(f)
            } else {
                BoltType::from(n.to_string())
            }
        }
        serde_json::Value::Bool(b) => BoltType::from(*b),
        serde_json::Value::Null => BoltType::Null(neo4rs::BoltNull),
        other => BoltType::from(other.to_string()),
    }
}

/// Convert a serializable entity to a HashMap<BoltString, BoltType> for Neo4j.
///
/// All scalar fields become typed properties. Null fields are included
/// as BoltType::Null. A `__data` property is added with the full JSON string.
fn entity_to_bolt_props<T: Serialize>(entity: &T) -> Result<BoltType> {
    let json =
        serde_json::to_value(entity).map_err(|e| anyhow!("Failed to serialize entity: {}", e))?;

    let obj = json
        .as_object()
        .ok_or_else(|| anyhow!("Expected JSON object"))?;

    let mut map = BoltMap::new();
    for (key, value) in obj {
        map.put(BoltString::from(key.as_str()), json_value_to_bolt(value));
    }

    // Add __data with the full JSON string for reliable deserialization
    let json_str = serde_json::to_string(entity)
        .map_err(|e| anyhow!("Failed to serialize entity to string: {}", e))?;
    map.put(BoltString::from("__data"), BoltType::from(json_str));

    Ok(BoltType::Map(map))
}

/// Extract the `__data` JSON string from a Neo4j Node and deserialize to T.
fn node_to_entity<T: DeserializeOwned>(node: &Node) -> Result<T> {
    let data: String = node
        .get("__data")
        .map_err(|_| anyhow!("Missing __data property on node"))?;
    serde_json::from_str(&data)
        .map_err(|e| anyhow!("Failed to deserialize entity from __data: {}", e))
}

/// Parse a search value string into the appropriate BoltType.
///
/// Tries boolean, integer, float, then falls back to string.
/// For search matching, we need the value type to match the stored property type.
fn parse_search_value(value: &str) -> BoltType {
    match value {
        "true" => BoltType::from(true),
        "false" => BoltType::from(false),
        _ => {
            if let Ok(i) = value.parse::<i64>() {
                return BoltType::from(i);
            }
            if value.contains('.')
                && let Ok(f) = value.parse::<f64>()
            {
                return BoltType::from(f);
            }
            BoltType::from(value.to_string())
        }
    }
}

// ---------------------------------------------------------------------------
// Neo4jDataService<T>
// ---------------------------------------------------------------------------

/// Generic data storage service backed by Neo4j.
///
/// Each entity type gets its own node label from `T::resource_name_singular()`.
///
/// # Example
///
/// ```rust,ignore
/// use neo4rs::Graph;
/// use this::storage::Neo4jDataService;
///
/// let graph = Graph::new("127.0.0.1:7687", "neo4j", "password").await?;
/// let service = Neo4jDataService::<MyEntity>::new(graph);
/// ```
#[derive(Clone)]
pub struct Neo4jDataService<T> {
    graph: Graph,
    _marker: std::marker::PhantomData<T>,
}

impl<T> Neo4jDataService<T> {
    pub fn new(graph: Graph) -> Self {
        Self {
            graph,
            _marker: std::marker::PhantomData,
        }
    }

    pub fn graph(&self) -> &Graph {
        &self.graph
    }
}

impl<T: Data + Serialize + DeserializeOwned> Neo4jDataService<T> {
    /// Node label for this entity type (e.g., "user", "order").
    fn label() -> &'static str {
        T::resource_name_singular()
    }

    /// Create indexes and constraints for this entity type.
    ///
    /// Creates:
    /// - Uniqueness constraint on `id` (also serves as an index)
    /// - Index on `name` for common lookups
    /// - Index on `entity_type` for type-scoped queries
    ///
    /// This method is idempotent — safe to call on every startup.
    pub async fn ensure_indexes(&self) -> Result<()> {
        let label = Self::label();

        // Uniqueness constraint on id (implicitly creates an index)
        let constraint = format!(
            "CREATE CONSTRAINT IF NOT EXISTS FOR (n:`{}`) REQUIRE n.id IS UNIQUE",
            label
        );
        self.graph
            .run(query(&constraint))
            .await
            .map_err(|e| anyhow!("Failed to create uniqueness constraint: {}", e))?;

        // Index on name for search
        let name_idx = format!("CREATE INDEX IF NOT EXISTS FOR (n:`{}`) ON (n.name)", label);
        self.graph
            .run(query(&name_idx))
            .await
            .map_err(|e| anyhow!("Failed to create name index: {}", e))?;

        // Index on entity_type for filtered listing
        let type_idx = format!(
            "CREATE INDEX IF NOT EXISTS FOR (n:`{}`) ON (n.entity_type)",
            label
        );
        self.graph
            .run(query(&type_idx))
            .await
            .map_err(|e| anyhow!("Failed to create entity_type index: {}", e))?;

        Ok(())
    }
}

#[async_trait]
impl<T: Data + Serialize + DeserializeOwned> DataService<T> for Neo4jDataService<T> {
    async fn create(&self, entity: T) -> Result<T> {
        let props = entity_to_bolt_props(&entity)?;
        let id = entity.id().to_string();

        // MERGE on id to get upsert behavior — avoids creating duplicate nodes
        // when the same UUID is inserted twice (Neo4j CREATE always creates a
        // new node regardless of property values).
        let cypher = format!(
            "MERGE (n:`{}` {{id: $id}}) SET n = $props RETURN n",
            Self::label()
        );

        let mut result = self
            .graph
            .execute(query(&cypher).param("id", id).param("props", props))
            .await
            .map_err(|e| anyhow!("Failed to create entity: {}", e))?;

        let row = result
            .next()
            .await
            .map_err(|e| anyhow!("Failed to read result: {}", e))?
            .ok_or_else(|| anyhow!("No result returned from CREATE"))?;

        let node: Node = row
            .get("n")
            .map_err(|e| anyhow!("Failed to get node from row: {}", e))?;

        node_to_entity(&node)
    }

    async fn get(&self, id: &Uuid) -> Result<Option<T>> {
        let cypher = format!("MATCH (n:`{}` {{id: $id}}) RETURN n", Self::label());

        let mut result = self
            .graph
            .execute(query(&cypher).param("id", id.to_string()))
            .await
            .map_err(|e| anyhow!("Failed to get entity: {}", e))?;

        match result
            .next()
            .await
            .map_err(|e| anyhow!("Failed to read result: {}", e))?
        {
            Some(row) => {
                let node: Node = row
                    .get("n")
                    .map_err(|e| anyhow!("Failed to get node: {}", e))?;
                Ok(Some(node_to_entity(&node)?))
            }
            None => Ok(None),
        }
    }

    async fn list(&self) -> Result<Vec<T>> {
        let cypher = format!(
            "MATCH (n:`{}`) RETURN n ORDER BY n.created_at DESC",
            Self::label()
        );

        let mut result = self
            .graph
            .execute(query(&cypher))
            .await
            .map_err(|e| anyhow!("Failed to list entities: {}", e))?;

        let mut entities = Vec::new();
        while let Some(row) = result
            .next()
            .await
            .map_err(|e| anyhow!("Failed to iterate: {}", e))?
        {
            let node: Node = row
                .get("n")
                .map_err(|e| anyhow!("Failed to get node: {}", e))?;
            entities.push(node_to_entity(&node)?);
        }

        Ok(entities)
    }

    async fn update(&self, id: &Uuid, entity: T) -> Result<T> {
        let props = entity_to_bolt_props(&entity)?;
        let cypher = format!(
            "MATCH (n:`{}` {{id: $id}}) SET n = $props RETURN n",
            Self::label()
        );

        let mut result = self
            .graph
            .execute(
                query(&cypher)
                    .param("id", id.to_string())
                    .param("props", props),
            )
            .await
            .map_err(|e| anyhow!("Failed to update entity: {}", e))?;

        match result
            .next()
            .await
            .map_err(|e| anyhow!("Failed to read result: {}", e))?
        {
            Some(row) => {
                let node: Node = row
                    .get("n")
                    .map_err(|e| anyhow!("Failed to get node: {}", e))?;
                node_to_entity(&node)
            }
            None => Err(anyhow!("Entity not found: {}", id)),
        }
    }

    async fn delete(&self, id: &Uuid) -> Result<()> {
        let cypher = format!("MATCH (n:`{}` {{id: $id}}) DELETE n", Self::label());

        self.graph
            .run(query(&cypher).param("id", id.to_string()))
            .await
            .map_err(|e| anyhow!("Failed to delete entity: {}", e))?;

        Ok(())
    }

    async fn search(&self, field: &str, value: &str) -> Result<Vec<T>> {
        // Build Cypher with field name interpolated (safe: field comes from our code)
        // and value as a parameterized query argument with type-smart parsing
        let cypher = format!(
            "MATCH (n:`{}`) WHERE n.`{}` = $value RETURN n",
            Self::label(),
            field
        );

        let bolt_value = parse_search_value(value);

        let mut result = self
            .graph
            .execute(query(&cypher).param("value", bolt_value))
            .await
            .map_err(|e| anyhow!("Failed to search entities: {}", e))?;

        let mut entities = Vec::new();
        while let Some(row) = result
            .next()
            .await
            .map_err(|e| anyhow!("Failed to iterate: {}", e))?
        {
            let node: Node = row
                .get("n")
                .map_err(|e| anyhow!("Failed to get node: {}", e))?;
            entities.push(node_to_entity(&node)?);
        }

        Ok(entities)
    }
}

// ---------------------------------------------------------------------------
// Neo4jLinkService
// ---------------------------------------------------------------------------

/// Link storage service backed by Neo4j.
///
/// Links are stored as nodes with label `_Link` (not as native Neo4j
/// relationships) to maintain compatibility with the `LinkService` contract.
///
/// # Example
///
/// ```rust,ignore
/// use neo4rs::Graph;
/// use this::storage::Neo4jLinkService;
///
/// let graph = Graph::new("127.0.0.1:7687", "neo4j", "password").await?;
/// let service = Neo4jLinkService::new(graph);
/// ```
#[derive(Clone)]
pub struct Neo4jLinkService {
    graph: Graph,
}

impl Neo4jLinkService {
    pub fn new(graph: Graph) -> Self {
        Self { graph }
    }

    pub fn graph(&self) -> &Graph {
        &self.graph
    }

    /// Create indexes on the `_Link` nodes for efficient querying.
    ///
    /// Creates:
    /// - Uniqueness constraint on `id`
    /// - Index on `source_id` for `find_by_source`
    /// - Index on `target_id` for `find_by_target`
    /// - Composite index on `source_id, link_type` for filtered queries
    /// - Composite index on `target_id, link_type` for filtered queries
    ///
    /// This method is idempotent — safe to call on every startup.
    pub async fn ensure_indexes(&self) -> Result<()> {
        let queries = [
            "CREATE CONSTRAINT IF NOT EXISTS FOR (l:`_Link`) REQUIRE l.id IS UNIQUE",
            "CREATE INDEX IF NOT EXISTS FOR (l:`_Link`) ON (l.source_id)",
            "CREATE INDEX IF NOT EXISTS FOR (l:`_Link`) ON (l.target_id)",
            "CREATE INDEX IF NOT EXISTS FOR (l:`_Link`) ON (l.source_id, l.link_type)",
            "CREATE INDEX IF NOT EXISTS FOR (l:`_Link`) ON (l.target_id, l.link_type)",
        ];

        for cypher in &queries {
            self.graph
                .run(query(cypher))
                .await
                .map_err(|e| anyhow!("Failed to create _Link index: {}", e))?;
        }

        Ok(())
    }
}

#[async_trait]
impl LinkService for Neo4jLinkService {
    async fn create(&self, link: LinkEntity) -> Result<LinkEntity> {
        let props = entity_to_bolt_props(&link)?;

        let mut result = self
            .graph
            .execute(query("CREATE (l:`_Link`) SET l = $props RETURN l").param("props", props))
            .await
            .map_err(|e| anyhow!("Failed to create link: {}", e))?;

        let row = result
            .next()
            .await
            .map_err(|e| anyhow!("Failed to read result: {}", e))?
            .ok_or_else(|| anyhow!("No result from CREATE"))?;

        let node: Node = row
            .get("l")
            .map_err(|e| anyhow!("Failed to get node: {}", e))?;

        node_to_entity(&node)
    }

    async fn get(&self, id: &Uuid) -> Result<Option<LinkEntity>> {
        let mut result = self
            .graph
            .execute(query("MATCH (l:`_Link` {id: $id}) RETURN l").param("id", id.to_string()))
            .await
            .map_err(|e| anyhow!("Failed to get link: {}", e))?;

        match result
            .next()
            .await
            .map_err(|e| anyhow!("Failed to read result: {}", e))?
        {
            Some(row) => {
                let node: Node = row
                    .get("l")
                    .map_err(|e| anyhow!("Failed to get node: {}", e))?;
                Ok(Some(node_to_entity(&node)?))
            }
            None => Ok(None),
        }
    }

    async fn list(&self) -> Result<Vec<LinkEntity>> {
        let mut result = self
            .graph
            .execute(query(
                "MATCH (l:`_Link`) RETURN l ORDER BY l.created_at DESC",
            ))
            .await
            .map_err(|e| anyhow!("Failed to list links: {}", e))?;

        let mut links = Vec::new();
        while let Some(row) = result
            .next()
            .await
            .map_err(|e| anyhow!("Failed to iterate: {}", e))?
        {
            let node: Node = row
                .get("l")
                .map_err(|e| anyhow!("Failed to get node: {}", e))?;
            links.push(node_to_entity(&node)?);
        }

        Ok(links)
    }

    async fn find_by_source(
        &self,
        source_id: &Uuid,
        link_type: Option<&str>,
        _target_type: Option<&str>,
    ) -> Result<Vec<LinkEntity>> {
        let q = if let Some(lt) = link_type {
            query("MATCH (l:`_Link` {source_id: $sid, link_type: $lt}) RETURN l ORDER BY l.created_at DESC")
                .param("sid", source_id.to_string())
                .param("lt", lt.to_string())
        } else {
            query("MATCH (l:`_Link` {source_id: $sid}) RETURN l ORDER BY l.created_at DESC")
                .param("sid", source_id.to_string())
        };

        let mut result = self
            .graph
            .execute(q)
            .await
            .map_err(|e| anyhow!("Failed to find links by source: {}", e))?;

        let mut links = Vec::new();
        while let Some(row) = result
            .next()
            .await
            .map_err(|e| anyhow!("Failed to iterate: {}", e))?
        {
            let node: Node = row
                .get("l")
                .map_err(|e| anyhow!("Failed to get node: {}", e))?;
            links.push(node_to_entity(&node)?);
        }

        Ok(links)
    }

    async fn find_by_target(
        &self,
        target_id: &Uuid,
        link_type: Option<&str>,
        _source_type: Option<&str>,
    ) -> Result<Vec<LinkEntity>> {
        let q = if let Some(lt) = link_type {
            query("MATCH (l:`_Link` {target_id: $tid, link_type: $lt}) RETURN l ORDER BY l.created_at DESC")
                .param("tid", target_id.to_string())
                .param("lt", lt.to_string())
        } else {
            query("MATCH (l:`_Link` {target_id: $tid}) RETURN l ORDER BY l.created_at DESC")
                .param("tid", target_id.to_string())
        };

        let mut result = self
            .graph
            .execute(q)
            .await
            .map_err(|e| anyhow!("Failed to find links by target: {}", e))?;

        let mut links = Vec::new();
        while let Some(row) = result
            .next()
            .await
            .map_err(|e| anyhow!("Failed to iterate: {}", e))?
        {
            let node: Node = row
                .get("l")
                .map_err(|e| anyhow!("Failed to get node: {}", e))?;
            links.push(node_to_entity(&node)?);
        }

        Ok(links)
    }

    async fn update(&self, id: &Uuid, link: LinkEntity) -> Result<LinkEntity> {
        let props = entity_to_bolt_props(&link)?;

        let mut result = self
            .graph
            .execute(
                query("MATCH (l:`_Link` {id: $id}) SET l = $props RETURN l")
                    .param("id", id.to_string())
                    .param("props", props),
            )
            .await
            .map_err(|e| anyhow!("Failed to update link: {}", e))?;

        match result
            .next()
            .await
            .map_err(|e| anyhow!("Failed to read result: {}", e))?
        {
            Some(row) => {
                let node: Node = row
                    .get("l")
                    .map_err(|e| anyhow!("Failed to get node: {}", e))?;
                node_to_entity(&node)
            }
            None => Err(anyhow!("Link not found: {}", id)),
        }
    }

    async fn delete(&self, id: &Uuid) -> Result<()> {
        self.graph
            .run(query("MATCH (l:`_Link` {id: $id}) DELETE l").param("id", id.to_string()))
            .await
            .map_err(|e| anyhow!("Failed to delete link: {}", e))?;

        Ok(())
    }

    async fn delete_by_entity(&self, entity_id: &Uuid) -> Result<()> {
        let eid = entity_id.to_string();
        self.graph
            .run(
                query("MATCH (l:`_Link`) WHERE l.source_id = $eid OR l.target_id = $eid DELETE l")
                    .param("eid", eid),
            )
            .await
            .map_err(|e| anyhow!("Failed to delete links by entity: {}", e))?;

        Ok(())
    }
}

#[cfg(test)]
#[cfg(feature = "neo4j")]
mod tests {
    use super::*;
    use serde_json::json;

    // === json_value_to_bolt ===

    #[test]
    fn test_json_value_to_bolt_string() {
        let val = json!("hello");
        let bolt = json_value_to_bolt(&val);
        // BoltType::String variant
        assert!(
            matches!(bolt, BoltType::String(_)),
            "expected String variant, got: {:?}",
            bolt
        );
    }

    #[test]
    fn test_json_value_to_bolt_integer() {
        let val = json!(42);
        let bolt = json_value_to_bolt(&val);
        assert!(
            matches!(bolt, BoltType::Integer(_)),
            "expected Integer variant, got: {:?}",
            bolt
        );
    }

    #[test]
    fn test_json_value_to_bolt_float() {
        let val = json!(3.15);
        let bolt = json_value_to_bolt(&val);
        // JSON numbers that have decimals should become Float
        assert!(
            matches!(bolt, BoltType::Float(_)),
            "expected Float variant, got: {:?}",
            bolt
        );
    }

    #[test]
    fn test_json_value_to_bolt_bool_true() {
        let val = json!(true);
        let bolt = json_value_to_bolt(&val);
        assert!(
            matches!(bolt, BoltType::Boolean(_)),
            "expected Boolean variant, got: {:?}",
            bolt
        );
    }

    #[test]
    fn test_json_value_to_bolt_bool_false() {
        let val = json!(false);
        let bolt = json_value_to_bolt(&val);
        assert!(
            matches!(bolt, BoltType::Boolean(_)),
            "expected Boolean variant, got: {:?}",
            bolt
        );
    }

    #[test]
    fn test_json_value_to_bolt_null() {
        let val = json!(null);
        let bolt = json_value_to_bolt(&val);
        assert!(
            matches!(bolt, BoltType::Null(_)),
            "expected Null variant, got: {:?}",
            bolt
        );
    }

    #[test]
    fn test_json_value_to_bolt_object_becomes_string() {
        let val = json!({"nested": "object"});
        let bolt = json_value_to_bolt(&val);
        // Objects/Arrays are serialized to JSON string
        assert!(
            matches!(bolt, BoltType::String(_)),
            "expected String variant for object, got: {:?}",
            bolt
        );
    }

    #[test]
    fn test_json_value_to_bolt_array_becomes_string() {
        let val = json!([1, 2, 3]);
        let bolt = json_value_to_bolt(&val);
        assert!(
            matches!(bolt, BoltType::String(_)),
            "expected String variant for array, got: {:?}",
            bolt
        );
    }

    // === parse_search_value ===

    #[test]
    fn test_parse_search_value_true() {
        let bolt = parse_search_value("true");
        assert!(
            matches!(bolt, BoltType::Boolean(_)),
            "expected Boolean for 'true', got: {:?}",
            bolt
        );
    }

    #[test]
    fn test_parse_search_value_false() {
        let bolt = parse_search_value("false");
        assert!(
            matches!(bolt, BoltType::Boolean(_)),
            "expected Boolean for 'false', got: {:?}",
            bolt
        );
    }

    #[test]
    fn test_parse_search_value_integer() {
        let bolt = parse_search_value("42");
        assert!(
            matches!(bolt, BoltType::Integer(_)),
            "expected Integer for '42', got: {:?}",
            bolt
        );
    }

    #[test]
    fn test_parse_search_value_negative_integer() {
        let bolt = parse_search_value("-7");
        assert!(
            matches!(bolt, BoltType::Integer(_)),
            "expected Integer for '-7', got: {:?}",
            bolt
        );
    }

    #[test]
    fn test_parse_search_value_float() {
        let bolt = parse_search_value("3.15");
        assert!(
            matches!(bolt, BoltType::Float(_)),
            "expected Float for '3.15', got: {:?}",
            bolt
        );
    }

    #[test]
    fn test_parse_search_value_string_fallback() {
        let bolt = parse_search_value("hello world");
        assert!(
            matches!(bolt, BoltType::String(_)),
            "expected String for 'hello world', got: {:?}",
            bolt
        );
    }

    #[test]
    fn test_parse_search_value_number_without_dot_is_integer() {
        // "100" should be parsed as Integer, not Float
        let bolt = parse_search_value("100");
        assert!(
            matches!(bolt, BoltType::Integer(_)),
            "expected Integer for '100', got: {:?}",
            bolt
        );
    }

    // === entity_to_bolt_props ===

    #[test]
    fn test_entity_to_bolt_props_returns_map() {
        #[derive(Serialize)]
        struct Simple {
            name: String,
            count: i32,
        }
        let entity = Simple {
            name: "test".to_string(),
            count: 5,
        };
        let result = entity_to_bolt_props(&entity).expect("should convert");
        assert!(
            matches!(result, BoltType::Map(_)),
            "expected Map variant, got: {:?}",
            result
        );
    }

    #[test]
    fn test_entity_to_bolt_props_includes_data_key() {
        #[derive(Serialize)]
        struct Item {
            id: String,
        }
        let entity = Item {
            id: "abc".to_string(),
        };
        let result = entity_to_bolt_props(&entity).expect("should convert");
        if let BoltType::Map(map) = result {
            // The map should contain __data key
            let has_data = map.value.iter().any(|(k, _)| k.value == "__data");
            assert!(has_data, "map should contain __data key");
        } else {
            panic!("expected Map variant");
        }
    }

    #[test]
    fn test_entity_to_bolt_props_non_object_returns_error() {
        // A bare string will serialize to a JSON string, not an object
        let result = entity_to_bolt_props(&"not an object");
        assert!(result.is_err(), "non-object should return error");
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("Expected JSON object"),
            "error should mention JSON object: {}",
            err
        );
    }
}