tideorm 0.4.5

A developer-friendly ORM for Rust with clean, expressive syntax
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
//! Translations System
//!
//! This module provides translation functionality for TideORM models.
//!
//! ## Overview
//!
//! Translations allow you to store localized content in a JSONB column with
//! the format: `{field_name: {lang_code: "value", ...}, ...}`
//!
//! Example JSONB structure:
//! ```json
//! {
//!     "name": {"en": "Product Name", "ar": "اسم المنتج"},
//!     "description": {"en": "Description", "ar": "الوصف"}
//! }
//! ```
//!
//! ## Setup
//!
//! Add a `translations` JSONB column to your table and use the `#[tide(translatable)]` attribute:
//!
//! ```rust,ignore
//! #[derive(Model)]
//! #[tide(table = "products")]
//! #[tide(translatable = "name,description")]
//! pub struct Product {
//!     #[tide(primary_key, auto_increment)]
//!     pub id: i64,
//!     
//!     // Default/fallback values stored directly on the model
//!     pub name: String,
//!     pub description: String,
//!     
//!     pub price: f64,
//!     
//!     // JSONB column storing translations
//!     pub translations: Option<Json>,
//! }
//! ```
//!
//! ## Usage
//!
//! ### Setting Translations
//!
//! ```rust,ignore
//! // Set translation for a field
//! product.set_translation("name", "ar", "اسم المنتج")?;
//! product.set_translation("description", "ar", "وصف المنتج")?;
//!
//! // Set multiple translations at once
//! product.set_translations("name", hashmap! {
//!     "en" => "Product Name",
//!     "ar" => "اسم المنتج",
//!     "fr" => "Nom du produit",
//! })?;
//!
//! product.update().await?;
//! ```
//!
//! ### Getting Translations
//!
//! ```rust,ignore
//! // Get translation for specific language
//! let name_ar = product.get_translation("name", "ar")?;
//!
//! // Get translation with fallback chain
//! let name = product.get_translated("name", "ar")?; // Falls back to default if not found
//!
//! // Get all translations for a field
//! let all_names = product.get_all_translations("name")?;
//! ```
//!
//! ### JSON Output with Translations
//!
//! ```rust,ignore
//! // Get model as JSON with translated fields
//! let mut opts = HashMap::new();
//! opts.insert("language".to_string(), "ar".to_string());
//! let json = product.to_json(Some(opts));
//!
//! // Result: {"id": 1, "name": "اسم المنتج", "description": "وصف المنتج", ...}
//! // Note: The translations JSONB column is removed from output
//! ```

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Translation data container
///
/// Stores translations in the format: `{field: {lang: value}}`
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TranslationsData {
    #[serde(flatten)]
    fields: HashMap<String, FieldTranslations>,
}

/// Translations for a single field
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct FieldTranslations {
    #[serde(flatten)]
    translations: HashMap<String, serde_json::Value>,
}

impl FieldTranslations {
    /// Create empty field translations
    pub fn new() -> Self {
        Self { translations: HashMap::new() }
    }
    
    /// Get translation for a language
    pub fn get(&self, lang: &str) -> Option<&serde_json::Value> {
        self.translations.get(lang)
    }
    
    /// Set translation for a language
    pub fn set(&mut self, lang: &str, value: impl Into<serde_json::Value>) {
        self.translations.insert(lang.to_string(), value.into());
    }
    
    /// Remove translation for a language
    pub fn remove(&mut self, lang: &str) {
        self.translations.remove(lang);
    }
    
    /// Get all translations as HashMap
    pub fn all(&self) -> &HashMap<String, serde_json::Value> {
        &self.translations
    }
    
    /// Check if has translation for language
    pub fn has(&self, lang: &str) -> bool {
        self.translations.contains_key(lang)
    }
    
    /// Get available languages
    pub fn languages(&self) -> Vec<&String> {
        self.translations.keys().collect()
    }
}

impl TranslationsData {
    /// Create empty translations data
    pub fn new() -> Self {
        Self { fields: HashMap::new() }
    }
    
    /// Create from JSON value
    pub fn from_json(value: &serde_json::Value) -> Self {
        match value {
            serde_json::Value::Object(map) => {
                let mut fields = HashMap::new();
                for (field_name, field_value) in map {
                    if let serde_json::Value::Object(lang_map) = field_value {
                        let mut translations = HashMap::new();
                        for (lang, trans_value) in lang_map {
                            translations.insert(lang.clone(), trans_value.clone());
                        }
                        fields.insert(field_name.clone(), FieldTranslations { translations });
                    }
                }
                Self { fields }
            }
            _ => Self::new(),
        }
    }
    
    /// Convert to JSON value
    pub fn to_json(&self) -> serde_json::Value {
        let mut map = serde_json::Map::new();
        for (field, trans) in &self.fields {
            let mut lang_map = serde_json::Map::new();
            for (lang, value) in &trans.translations {
                lang_map.insert(lang.clone(), value.clone());
            }
            map.insert(field.clone(), serde_json::Value::Object(lang_map));
        }
        serde_json::Value::Object(map)
    }
    
    /// Get translations for a field
    pub fn get_field(&self, field: &str) -> Option<&FieldTranslations> {
        self.fields.get(field)
    }
    
    /// Get mutable translations for a field
    pub fn get_field_mut(&mut self, field: &str) -> &mut FieldTranslations {
        self.fields.entry(field.to_string()).or_insert_with(FieldTranslations::new)
    }
    
    /// Get translation for a specific field and language
    pub fn get(&self, field: &str, lang: &str) -> Option<&serde_json::Value> {
        self.fields.get(field)?.get(lang)
    }
    
    /// Set translation for a specific field and language
    pub fn set(&mut self, field: &str, lang: &str, value: impl Into<serde_json::Value>) {
        self.get_field_mut(field).set(lang, value);
    }
    
    /// Remove translation for a field and language
    pub fn remove(&mut self, field: &str, lang: &str) {
        if let Some(field_trans) = self.fields.get_mut(field) {
            field_trans.remove(lang);
        }
    }
    
    /// Remove all translations for a field
    pub fn remove_field(&mut self, field: &str) {
        self.fields.remove(field);
    }
    
    /// Check if field has translations
    pub fn has_translations(&self, field: &str) -> bool {
        self.fields.get(field)
            .map(|f| !f.translations.is_empty())
            .unwrap_or(false)
    }
    
    /// Get all translatable fields
    pub fn fields(&self) -> Vec<&String> {
        self.fields.keys().collect()
    }
}

/// Trait for models with translations
///
/// This trait is automatically implemented for models with translation configuration.
/// You can also implement it manually for custom behavior.
pub trait HasTranslations {
    /// Get the list of translatable field names
    fn translatable_fields() -> Vec<&'static str>;
    
    /// Get allowed languages for translations
    fn allowed_languages() -> Vec<String>;
    
    /// Get the fallback language
    fn fallback_language() -> String;
    
    /// Get the current translations data from the model
    fn get_translations_data(&self) -> Result<TranslationsData, TranslationError>;
    
    /// Set the translations data on the model
    fn set_translations_data(&mut self, data: TranslationsData) -> Result<(), TranslationError>;
    
    /// Get the default (non-translated) value for a field
    fn get_default_value(&self, field: &str) -> Result<serde_json::Value, TranslationError>;
    
    // =========================================================================
    // SET TRANSLATION METHODS
    // =========================================================================
    
    /// Set a translation for a field in a specific language
    ///
    /// # Example
    /// ```rust,ignore
    /// product.set_translation("name", "ar", "اسم المنتج")?;
    /// product.set_translation("name", "fr", "Nom du produit")?;
    /// product.update().await?;
    /// ```
    fn set_translation(&mut self, field: &str, lang: &str, value: impl Into<serde_json::Value>) -> Result<(), TranslationError> {
        self.validate_field(field)?;
        self.validate_language(lang)?;
        
        let mut data = self.get_translations_data()?;
        data.set(field, lang, value);
        self.set_translations_data(data)
    }
    
    /// Set multiple translations for a field at once
    ///
    /// # Example
    /// ```rust,ignore
    /// let mut names = HashMap::new();
    /// names.insert("en", "Product Name");
    /// names.insert("ar", "اسم المنتج");
    /// names.insert("fr", "Nom du produit");
    /// product.set_translations("name", names)?;
    /// ```
    fn set_translations<V: Into<serde_json::Value>>(&mut self, field: &str, translations: HashMap<&str, V>) -> Result<(), TranslationError> {
        self.validate_field(field)?;
        
        let mut data = self.get_translations_data()?;
        for (lang, value) in translations {
            self.validate_language(lang)?;
            data.set(field, lang, value);
        }
        self.set_translations_data(data)
    }
    
    /// Set all translations for a field from a map (replaces existing)
    ///
    /// # Example
    /// ```rust,ignore
    /// product.sync_translations("name", hashmap! {
    ///     "en" => "New Name",
    ///     "ar" => "اسم جديد",
    /// })?;
    /// ```
    fn sync_translations<V: Into<serde_json::Value>>(&mut self, field: &str, translations: HashMap<&str, V>) -> Result<(), TranslationError> {
        self.validate_field(field)?;
        
        let mut data = self.get_translations_data()?;
        data.remove_field(field);
        for (lang, value) in translations {
            self.validate_language(lang)?;
            data.set(field, lang, value);
        }
        self.set_translations_data(data)
    }
    
    // =========================================================================
    // GET TRANSLATION METHODS
    // =========================================================================
    
    /// Get the translation for a field in a specific language
    ///
    /// Returns `None` if no translation exists for that language.
    ///
    /// # Example
    /// ```rust,ignore
    /// if let Some(name) = product.get_translation("name", "ar")? {
    ///     println!("Arabic name: {}", name);
    /// }
    /// ```
    fn get_translation(&self, field: &str, lang: &str) -> Result<Option<serde_json::Value>, TranslationError> {
        let data = self.get_translations_data()?;
        Ok(data.get(field, lang).cloned())
    }
    
    /// Get the translation with fallback chain
    ///
    /// Tries: requested language -> fallback language -> default field value
    ///
    /// # Example
    /// ```rust,ignore
    /// // If Arabic not available, falls back to English, then to field value
    /// let name = product.get_translated("name", "ar")?;
    /// ```
    fn get_translated(&self, field: &str, lang: &str) -> Result<serde_json::Value, TranslationError> {
        let data = self.get_translations_data()?;
        let fallback = Self::fallback_language();
        
        // Try requested language
        if let Some(value) = data.get(field, lang) {
            return Ok(value.clone());
        }
        
        // Try fallback language
        if lang != fallback {
            if let Some(value) = data.get(field, &fallback) {
                return Ok(value.clone());
            }
        }
        
        // Fall back to default field value
        self.get_default_value(field)
    }
    
    /// Get all translations for a field
    ///
    /// # Example
    /// ```rust,ignore
    /// let all_names = product.get_all_translations("name")?;
    /// for (lang, value) in all_names {
    ///     println!("{}: {}", lang, value);
    /// }
    /// ```
    fn get_all_translations(&self, field: &str) -> Result<HashMap<String, serde_json::Value>, TranslationError> {
        let data = self.get_translations_data()?;
        Ok(data.get_field(field)
            .map(|f| f.all().clone())
            .unwrap_or_default())
    }
    
    /// Get translations for all fields in a specific language
    ///
    /// # Example
    /// ```rust,ignore
    /// let arabic = product.get_translations_for_language("ar")?;
    /// // Returns: {"name": "اسم المنتج", "description": "وصف المنتج"}
    /// ```
    fn get_translations_for_language(&self, lang: &str) -> Result<HashMap<String, serde_json::Value>, TranslationError> {
        let data = self.get_translations_data()?;
        let mut result = HashMap::new();
        
        for field in Self::translatable_fields() {
            if let Some(value) = data.get(field, lang) {
                result.insert(field.to_string(), value.clone());
            }
        }
        
        Ok(result)
    }
    
    // =========================================================================
    // REMOVE TRANSLATION METHODS
    // =========================================================================
    
    /// Remove a translation for a field in a specific language
    fn remove_translation(&mut self, field: &str, lang: &str) -> Result<(), TranslationError> {
        let mut data = self.get_translations_data()?;
        data.remove(field, lang);
        self.set_translations_data(data)
    }
    
    /// Remove all translations for a field
    fn remove_field_translations(&mut self, field: &str) -> Result<(), TranslationError> {
        let mut data = self.get_translations_data()?;
        data.remove_field(field);
        self.set_translations_data(data)
    }
    
    /// Clear all translations
    fn clear_translations(&mut self) -> Result<(), TranslationError> {
        self.set_translations_data(TranslationsData::new())
    }
    
    // =========================================================================
    // CHECK METHODS
    // =========================================================================
    
    /// Check if field has a translation for a language
    fn has_translation(&self, field: &str, lang: &str) -> Result<bool, TranslationError> {
        let data = self.get_translations_data()?;
        Ok(data.get(field, lang).is_some())
    }
    
    /// Check if field has any translations
    fn has_any_translation(&self, field: &str) -> Result<bool, TranslationError> {
        let data = self.get_translations_data()?;
        Ok(data.has_translations(field))
    }
    
    /// Get languages available for a field
    fn available_languages(&self, field: &str) -> Result<Vec<String>, TranslationError> {
        let data = self.get_translations_data()?;
        Ok(data.get_field(field)
            .map(|f| f.languages().into_iter().cloned().collect())
            .unwrap_or_default())
    }
    
    // =========================================================================
    // JSON OUTPUT
    // =========================================================================
    
    /// Convert model to JSON with translations applied
    ///
    /// This method:
    /// 1. Serializes the model to JSON
    /// 2. Replaces translatable fields with their translated values
    /// 3. Removes the raw `translations` JSONB column from output
    ///
    /// # Arguments
    /// * `options` - Optional HashMap with:
    ///   - `language`: Language code (e.g., "en", "ar", "fr")
    ///
    /// # Example
    /// ```rust,ignore
    /// // Without options (uses default values)
    /// let json = product.to_translated_json(None);
    ///
    /// // With Arabic translations
    /// let mut opts = HashMap::new();
    /// opts.insert("language".to_string(), "ar".to_string());
    /// let json = product.to_translated_json(Some(opts));
    /// ```
    fn to_translated_json(&self, options: Option<HashMap<String, String>>) -> serde_json::Value
    where
        Self: serde::Serialize,
    {
        let opts = options.unwrap_or_default();
        let fallback = Self::fallback_language();
        let requested_lang = opts.get("language")
            .map(|s| s.as_str())
            .unwrap_or(&fallback);
        
        // Serialize model to JSON
        let mut json = match serde_json::to_value(self) {
            Ok(serde_json::Value::Object(map)) => map,
            _ => return serde_json::json!({}),
        };
        
        // Get translations data
        let translations = json.get("translations")
            .map(|v| TranslationsData::from_json(v))
            .unwrap_or_default();
        
        // Apply translations to translatable fields
        for field in Self::translatable_fields() {
            // Try requested language first
            if let Some(value) = translations.get(field, requested_lang) {
                json.insert(field.to_string(), value.clone());
            } else if requested_lang != fallback {
                // Try fallback language
                if let Some(value) = translations.get(field, &fallback) {
                    json.insert(field.to_string(), value.clone());
                }
                // Otherwise keep the default value already in json
            }
        }
        
        // Remove the raw translations column from output
        json.remove("translations");
        
        serde_json::Value::Object(json)
    }
    
    /// Convert to JSON including all translations
    ///
    /// Useful for admin interfaces or APIs that need to show all translations.
    ///
    /// # Example
    /// ```rust,ignore
    /// let json = product.to_json_with_all_translations();
    /// // Result includes: {"name": "Default", "translations": {"name": {"en": "...", "ar": "..."}}}
    /// ```
    fn to_json_with_all_translations(&self) -> serde_json::Value
    where
        Self: serde::Serialize,
    {
        serde_json::to_value(self).unwrap_or(serde_json::json!({}))
    }
    
    // =========================================================================
    // HELPER METHODS
    // =========================================================================
    
    /// Validate that a field is translatable
    fn validate_field(&self, field: &str) -> Result<(), TranslationError> {
        if !Self::translatable_fields().contains(&field) {
            return Err(TranslationError::InvalidField(
                format!("'{}' is not a translatable field. Available: {:?}", field, Self::translatable_fields())
            ));
        }
        Ok(())
    }
    
    /// Validate that a language is allowed
    fn validate_language(&self, lang: &str) -> Result<(), TranslationError> {
        let allowed = Self::allowed_languages();
        if !allowed.iter().any(|l| l == lang) {
            return Err(TranslationError::InvalidLanguage(
                format!("'{}' is not an allowed language. Allowed: {:?}", lang, allowed)
            ));
        }
        Ok(())
    }
}

/// Helper to create translations from input data
///
/// Use this when processing form data or API requests that include translations.
///
/// # Example
/// ```rust,ignore
/// // Input format: {"name": {"en": "Name", "ar": "اسم"}, "description": {"en": "Desc"}}
/// let translations = TranslationInput::from_json(&input)?;
/// product.apply_translations(translations)?;
/// ```
#[derive(Debug, Clone)]
pub struct TranslationInput {
    /// Field translations
    pub fields: HashMap<String, HashMap<String, serde_json::Value>>,
}

impl TranslationInput {
    /// Create empty input
    pub fn new() -> Self {
        Self { fields: HashMap::new() }
    }
    
    /// Create from JSON value
    ///
    /// Expected format: `{"field": {"lang": "value", ...}, ...}`
    pub fn from_json(value: &serde_json::Value) -> Result<Self, TranslationError> {
        match value {
            serde_json::Value::Object(map) => {
                let mut fields = HashMap::new();
                for (field, trans) in map {
                    if let serde_json::Value::Object(lang_map) = trans {
                        let mut translations = HashMap::new();
                        for (lang, val) in lang_map {
                            translations.insert(lang.clone(), val.clone());
                        }
                        fields.insert(field.clone(), translations);
                    }
                }
                Ok(Self { fields })
            }
            _ => Err(TranslationError::ParseError("Expected JSON object".to_string())),
        }
    }
    
    /// Add a translation
    pub fn add(&mut self, field: &str, lang: &str, value: impl Into<serde_json::Value>) {
        self.fields
            .entry(field.to_string())
            .or_insert_with(HashMap::new)
            .insert(lang.to_string(), value.into());
    }
}

impl Default for TranslationInput {
    fn default() -> Self {
        Self::new()
    }
}

/// Extension trait for applying translation input to models
pub trait ApplyTranslations: HasTranslations {
    /// Apply translations from TranslationInput
    ///
    /// # Example
    /// ```rust,ignore
    /// let input = TranslationInput::from_json(&request_body["translations"])?;
    /// product.apply_translations(input)?;
    /// product.update().await?;
    /// ```
    fn apply_translations(&mut self, input: TranslationInput) -> Result<(), TranslationError> {
        let mut data = self.get_translations_data()?;
        
        for (field, translations) in input.fields {
            for (lang, value) in translations {
                data.set(&field, &lang, value);
            }
        }
        
        self.set_translations_data(data)
    }
}

// Implement ApplyTranslations for all HasTranslations
impl<T: HasTranslations> ApplyTranslations for T {}

/// Errors that can occur during translation operations
#[derive(Debug, Clone)]
pub enum TranslationError {
    /// Invalid or non-translatable field
    InvalidField(String),
    /// Invalid or disallowed language
    InvalidLanguage(String),
    /// Failed to parse translations data
    ParseError(String),
    /// Model doesn't support translations
    NotSupported,
}

impl std::fmt::Display for TranslationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TranslationError::InvalidField(msg) => write!(f, "Invalid field: {}", msg),
            TranslationError::InvalidLanguage(msg) => write!(f, "Invalid language: {}", msg),
            TranslationError::ParseError(msg) => write!(f, "Parse error: {}", msg),
            TranslationError::NotSupported => write!(f, "Model does not support translations"),
        }
    }
}

impl std::error::Error for TranslationError {}

impl From<TranslationError> for crate::Error {
    fn from(err: TranslationError) -> Self {
        crate::Error::query(err.to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_translations_data_basic() {
        let mut data = TranslationsData::new();
        
        data.set("name", "en", "Product");
        data.set("name", "ar", "منتج");
        
        assert_eq!(data.get("name", "en"), Some(&serde_json::json!("Product")));
        assert_eq!(data.get("name", "ar"), Some(&serde_json::json!("منتج")));
        assert_eq!(data.get("name", "fr"), None);
    }
    
    #[test]
    fn test_translations_data_from_json() {
        let json = serde_json::json!({
            "name": {"en": "Product", "ar": "منتج"},
            "description": {"en": "A great product"}
        });
        
        let data = TranslationsData::from_json(&json);
        
        assert_eq!(data.get("name", "en"), Some(&serde_json::json!("Product")));
        assert_eq!(data.get("name", "ar"), Some(&serde_json::json!("منتج")));
        assert_eq!(data.get("description", "en"), Some(&serde_json::json!("A great product")));
    }
    
    #[test]
    fn test_translations_data_to_json() {
        let mut data = TranslationsData::new();
        data.set("name", "en", "Product");
        data.set("name", "ar", "منتج");
        
        let json = data.to_json();
        let expected = serde_json::json!({
            "name": {"en": "Product", "ar": "منتج"}
        });
        
        assert_eq!(json, expected);
    }
    
    #[test]
    fn test_field_translations() {
        let mut field = FieldTranslations::new();
        
        field.set("en", "Hello");
        field.set("ar", "مرحبا");
        
        assert!(field.has("en"));
        assert!(field.has("ar"));
        assert!(!field.has("fr"));
        
        assert_eq!(field.languages().len(), 2);
        
        field.remove("ar");
        assert!(!field.has("ar"));
    }
    
    #[test]
    fn test_translation_input() {
        let mut input = TranslationInput::new();
        input.add("name", "en", "Product");
        input.add("name", "ar", "منتج");
        input.add("description", "en", "Description");
        
        assert_eq!(input.fields.len(), 2);
        assert_eq!(input.fields.get("name").unwrap().len(), 2);
    }
    
    #[test]
    fn test_translation_input_from_json() {
        let json = serde_json::json!({
            "name": {"en": "Product", "ar": "منتج"},
            "description": {"en": "A product"}
        });
        
        let input = TranslationInput::from_json(&json).unwrap();
        
        assert_eq!(input.fields.len(), 2);
        assert_eq!(
            input.fields.get("name").unwrap().get("en"),
            Some(&serde_json::json!("Product"))
        );
    }
}