use crate::storage::Error;
use pbbson::Model;
use pbbson::bson::{Bson, Document};
use serde_json::Value;
use std::collections::HashMap;

pub fn to_json(model: &Model, include_id: bool) -> Result<HashMap<String, Value>, Error> {
    // First pass; BSON DateTime to RFC3339
    let mut local_model = Model::default();
    for (k, v) in model.iter() {
        let v = match v {
            Bson::DateTime(dt) => Bson::String(dt.try_to_rfc3339_string().map_err(|e| Error::internal(e.to_string()))?),
            _ => v.clone(),
        };
        local_model.insert(k, v);
    }

    // Second pass; default BSON to JSON formatting
    let doc = Document::from(local_model);
    let json = serde_json::to_string(&doc).map_err(|e| Error::internal(e.to_string()))?;
    let mut map: HashMap<String, Value> = serde_json::from_str(&json).map_err(|e| Error::internal(e.to_string()))?;
    if !include_id {
        map.remove("id");
    }

    Ok(map)
}
