#![doc = include_str!("../README.md")]
#![warn(clippy::all, clippy::pedantic)]
#![allow(clippy::missing_errors_doc, clippy::cast_sign_loss)]

// Copyright (C) 2026 Ordinary Labs, LLC.
//
// SPDX-License-Identifier: AGPL-3.0-only

mod ffi;

use anyhow::bail;
use bytes::Bytes;
use flexbuffers::VectorReader;
use hashbrown::HashMap;
use http::{HeaderName, HeaderValue, StatusCode};
use parking_lot::RwLock;
use std::collections::BTreeMap;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use tracing::{Instrument, info_span, instrument};

use ordinary_auth::Auth;
use ordinary_config::{
    ContentDefinition, ModelConfig, OrdinaryConfig, QueryExpression, StoredCachePolicy,
    TemplateConfig, TemplateFfiVersion, TemplateRef, TemplateRefField, TemplateRefFieldBind,
};
use ordinary_storage::{ArtifactKind, CacheRead, RefDepth, Storage};
use ordinary_types::{Field, Kind};

use wasmtime::Module;

use ordinary_utils::REPORTING_ENDPOINTS;
pub use wasmtime::Engine;

#[cfg(feature = "studio")]
const IFRAME_RESIZER_CHILD_URL: &str = "https://cdn.jsdelivr.net/npm/@iframe-resizer/child@5.5.9";

#[derive(Clone, Debug, PartialEq)]
pub enum TemplateResult {
    Result(Bytes),
    StatusCode(StatusCode),
}

#[derive(Clone, Debug)]
enum Include {
    Field(u8, Kind),
    Fields(u8, Vec<Include>, bool),
}

impl Include {
    fn build_for_field(
        field: &Field,
        ref_field: &TemplateRefField,
        model_map: &HashMap<String, ModelConfig>,
        ref_depth: &mut RefDepth,
    ) -> anyhow::Result<Self> {
        let field_idx = field.idx;

        match &ref_field.fields {
            Some(nested_ref_fields) => {
                let mut nested = vec![];
                let mut is_list = false;

                let mut nested_field_map = HashMap::new();

                match &field.kind {
                    Kind::List { kind } => {
                        if let Kind::Object { name: _, fields } = &**kind {
                            for nested_field in fields {
                                nested_field_map.insert(nested_field.name.clone(), nested_field);
                            }

                            is_list = true;
                        } else {
                            bail!("cannot have nested fields on non object");
                        }
                    }
                    Kind::Object { name: _, fields } => {
                        for nested_field in fields {
                            nested_field_map.insert(nested_field.name.clone(), nested_field);
                        }
                    }
                    Kind::Ref {
                        model,
                        field: _,
                        many: _,
                    } => {
                        if let Some(model) = model_map.get(model) {
                            for nested_field in &model.fields {
                                nested_field_map.insert(nested_field.name.clone(), nested_field);
                            }

                            ref_depth.0.push(((field.idx, 1, None), RefDepth(vec![])));
                        }
                    }
                    _ => bail!("cannot have nested fields on non object"),
                }

                let mut fields_clone = nested_ref_fields.clone();
                fields_clone.sort_by_key(|a| a.idx);

                for nested_ref_field in fields_clone {
                    if let Some(nested_field) = nested_field_map.get(&nested_ref_field.name) {
                        nested.push(Self::build_for_field(
                            nested_field,
                            &nested_ref_field,
                            model_map,
                            ref_depth,
                        )?);
                    }
                }

                nested.shrink_to_fit();
                Ok(Include::Fields(field_idx, nested, is_list))
            }
            None => Ok(Include::Field(field_idx, field.kind.clone())),
        }
    }

    fn build_for_content(
        content_def: &ContentDefinition,
        template_ref: &TemplateRef,
    ) -> anyhow::Result<Vec<Self>> {
        let mut include_fields = vec![];

        let mut fields_clone = template_ref.fields.clone();
        fields_clone.sort_by_key(|a| a.idx);

        let mut content_def_field_map = HashMap::new();
        for field in &content_def.fields {
            content_def_field_map.insert(field.name.clone(), field);
        }

        for field in fields_clone {
            if let Some(def_field) = content_def_field_map.get(&field.name) {
                let include = Self::build_for_field(
                    def_field,
                    &field,
                    &HashMap::new(),
                    &mut RefDepth(vec![]),
                )?;
                include_fields.push(include);
            }
        }

        include_fields.shrink_to_fit();
        Ok(include_fields)
    }

    fn build_for_model(
        model_config: &ModelConfig,
        template_ref: &TemplateRef,
        model_map: &HashMap<String, ModelConfig>,
    ) -> anyhow::Result<(Vec<Self>, RefDepth)> {
        let mut include_fields = vec![];

        let mut fields_clone = template_ref.fields.clone();
        fields_clone.sort_by_key(|a| a.idx);

        let mut model_config_field_map = HashMap::new();
        for field in &model_config.fields {
            model_config_field_map.insert(field.name.clone(), field);
        }
        let mut ref_depth = RefDepth(vec![]);

        for field in fields_clone {
            if let Some(def_field) = model_config_field_map.get(&field.name) {
                let include = Self::build_for_field(def_field, &field, model_map, &mut ref_depth)?;
                include_fields.push(include);
            }
        }

        include_fields.shrink_to_fit();
        Ok((include_fields, ref_depth))
    }

    fn marry(
        &self,
        builder: &mut flexbuffers::VectorBuilder,
        reader: &VectorReader<&[u8]>,
    ) -> anyhow::Result<()> {
        match self {
            Include::Field(idx, kind) => {
                kind.copy_to(&reader.idx(*idx as usize), builder, None)?;
            }
            Include::Fields(idx, fields, is_list) => {
                let mut nested = builder.start_vector();
                let reader = reader.idx(*idx as usize).as_vector();

                if *is_list {
                    for list_reader in &reader {
                        let mut builder = nested.start_vector();

                        for field in fields {
                            field.marry(&mut builder, &list_reader.as_vector())?;
                        }

                        builder.end_vector();
                    }
                } else {
                    for field in fields {
                        field.marry(&mut nested, &reader)?;
                    }
                }

                nested.end_vector();
            }
        }

        Ok(())
    }
}

#[derive(Clone, Debug)]
enum QueryKind {
    /// path position, whether it's a wildcard
    Segment(usize, bool),
    /// token field idx
    Token(u8),
    /// if there is no query
    None,
}

#[derive(Clone, Debug)]
enum Query {
    /// model kind, field idx, type
    Model(
        u8,
        u8,
        Kind,
        RefDepth,
        Option<ordinary_storage::QueryExpression>,
    ),
    /// def idx, field idx, type
    Content(u8, u8, Kind),

    /// def idx
    ContentMulti(u8),
}

#[derive(Clone)]
pub struct Template {
    pub idx: u8,
    pub mime: HeaderValue,
    pub reporting_endpoints: (HeaderName, HeaderValue),
    pub config: TemplateConfig,

    pub cache_control: Option<String>,
    pub csp: Arc<RwLock<Option<HeaderValue>>>,

    globals: Option<Bytes>,
    fields: Option<Bytes>,

    engine: Engine,
    module: Arc<RwLock<Option<Module>>>,

    storage: Arc<Storage>,

    queries: Option<Vec<(Query, QueryKind, Vec<Include>)>>,
}

impl Template {
    #[allow(clippy::too_many_lines, clippy::too_many_arguments)]
    #[instrument(
        name = "template"
        skip_all,
        fields(i, nm),
        err
    )]
    pub fn new(
        domain: &str,
        secure: bool,

        src: Option<Bytes>,

        config: TemplateConfig,
        auth: Arc<Auth>,
        model_map: &HashMap<String, ModelConfig>,
        content_map: &HashMap<String, ContentDefinition>,

        globals: Option<Bytes>,
        fields: Option<Bytes>,

        engine: Engine,
        storage: Arc<Storage>,
    ) -> anyhow::Result<Template> {
        tracing::Span::current().record("i", config.idx);
        tracing::Span::current().record("nm", tracing::field::display(&config.name));

        let (module, csp) = if let Some(src) = src {
            let root = flexbuffers::Reader::get_root(src.as_ref())?;
            let root_vec = root.as_vector();

            if let Ok(module) = Module::new(&engine, root_vec.idx(1).as_blob().0) {
                let csp = if matches!(
                    config.mime.as_str(),
                    "text/html" | "text/html; charset=utf-8" | "text/xml"
                ) {
                    Some(HeaderValue::from_str(root_vec.idx(0).as_str())?)
                } else {
                    None
                };

                (
                    Arc::new(RwLock::new(Some(module))),
                    Arc::new(RwLock::new(csp)),
                )
            } else {
                (Arc::new(RwLock::new(None)), Arc::new(RwLock::new(None)))
            }
        } else {
            (Arc::new(RwLock::new(None)), Arc::new(RwLock::new(None)))
        };

        tracing::info!("init");

        let mut queries = vec![];

        // todo: disallow conflicting bindings

        if let Some(content_refs) = &config.content {
            for content_ref in content_refs {
                if let Some(content_def) = content_map.get(&content_ref.name) {
                    let mut def_fields_map = BTreeMap::new();

                    for field in &content_def.fields {
                        def_fields_map.insert(field.name.clone(), field);
                    }

                    let include_fields = Include::build_for_content(content_def, content_ref)?;

                    if content_ref.all.is_some() {
                        queries.push((
                            content_ref.idx,
                            Query::ContentMulti(content_def.idx),
                            QueryKind::None,
                            include_fields.clone(),
                        ));
                    }

                    for ref_field in &content_ref.fields {
                        if let Some(def_field) = def_fields_map.get(&ref_field.name)
                            && let Some(binding) = &ref_field.bind
                        {
                            match binding {
                                TemplateRefFieldBind::Segment {
                                    name,
                                    expression: _,
                                } => {
                                    let mut path_pos = None;

                                    for (i, segment) in config.route.split('/').enumerate() {
                                        if segment == format!("{{{name}}}") {
                                            path_pos = Some((i, name.starts_with('*')));
                                        }
                                    }

                                    if let Some((path_pos, is_wildcard)) = path_pos {
                                        queries.push((
                                            content_ref.idx,
                                            Query::Content(
                                                content_def.idx,
                                                def_field.idx,
                                                def_field.kind.clone(),
                                            ),
                                            QueryKind::Segment(path_pos, is_wildcard),
                                            include_fields.clone(),
                                        ));
                                    } else {
                                        bail!(
                                            "cannot bind to segment {{{name}}} as it is not present in the route"
                                        );
                                    }
                                }
                                TemplateRefFieldBind::Token {
                                    field,
                                    expression: _,
                                } => {
                                    let mut auth_field_idx = None;

                                    for auth_field in &auth.config.access_token.claims {
                                        if &auth_field.name == field {
                                            auth_field_idx = Some(auth_field.idx);
                                        }
                                    }

                                    if let Some(idx) = auth_field_idx {
                                        queries.push((
                                            content_ref.idx,
                                            Query::Content(
                                                content_def.idx,
                                                def_field.idx,
                                                def_field.kind.clone(),
                                            ),
                                            QueryKind::Token(idx),
                                            include_fields.clone(),
                                        ));
                                    } else {
                                        bail!("auth field {field} does not exist");
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        if let Some(model_refs) = &config.models {
            for model_ref in model_refs {
                if let Some(model_config) = model_map.get(&model_ref.name) {
                    let mut model_config_fields_map = BTreeMap::new();

                    let mut model_config = (*model_config).clone();

                    let uuid_field = Field {
                        idx: 0,
                        name: "uuid".into(),
                        kind: Kind::Uuid,
                        indexed: Some(true),
                        queryable: None,
                        searchable: None,
                        mapping: None,
                        doc: None,
                        encrypted: None,
                        compressed: None,
                    };

                    let mut new_fields = model_config.fields.clone();
                    new_fields.splice(0..0, vec![uuid_field]);

                    model_config.fields = new_fields;

                    for field in &model_config.fields {
                        model_config_fields_map.insert(field.name.clone(), field);
                    }

                    let (include_fields, ref_depth) =
                        Include::build_for_model(&model_config, model_ref, model_map)?;

                    for ref_field in &model_ref.fields {
                        if let Some(config_field) = model_config_fields_map.get(&ref_field.name)
                            && let Some(binding) = &ref_field.bind
                        {
                            match binding {
                                TemplateRefFieldBind::Segment { name, expression } => {
                                    let mut path_pos = None;

                                    for (i, segment) in config.route.split('/').enumerate() {
                                        if segment == format!("{{{name}}}") {
                                            path_pos = Some((i, name.starts_with('*')));
                                        }
                                    }

                                    let exp = match expression {
                                        Some(exp) => match exp {
                                            QueryExpression::Gte => {
                                                Some(ordinary_storage::QueryExpression::Gte)
                                            }
                                            QueryExpression::Lte => {
                                                Some(ordinary_storage::QueryExpression::Lte)
                                            }
                                            QueryExpression::Gt => {
                                                Some(ordinary_storage::QueryExpression::Gt)
                                            }
                                            QueryExpression::Lt => {
                                                Some(ordinary_storage::QueryExpression::Lt)
                                            }
                                            QueryExpression::Eq => {
                                                Some(ordinary_storage::QueryExpression::Eq)
                                            }
                                            QueryExpression::BeginsWith => {
                                                Some(ordinary_storage::QueryExpression::BeginsWith)
                                            }
                                        },
                                        None => None,
                                    };

                                    if let Some((path_pos, is_wildcard)) = path_pos {
                                        queries.push((
                                            model_ref.idx,
                                            Query::Model(
                                                model_config.idx,
                                                config_field.idx,
                                                config_field.kind.clone(),
                                                ref_depth.clone(),
                                                exp,
                                            ),
                                            QueryKind::Segment(path_pos, is_wildcard),
                                            include_fields.clone(),
                                        ));
                                    } else {
                                        bail!(
                                            "cannot bind to segment {{{name}}} as it is not present in the route"
                                        );
                                    }
                                }
                                TemplateRefFieldBind::Token { field, expression } => {
                                    let mut auth_field_idx = None;

                                    for auth_field in &auth.config.access_token.claims {
                                        if &auth_field.name == field {
                                            auth_field_idx = Some(auth_field.idx);
                                        }
                                    }

                                    let exp = match expression {
                                        Some(exp) => match exp {
                                            QueryExpression::Gte => {
                                                Some(ordinary_storage::QueryExpression::Gte)
                                            }
                                            QueryExpression::Lte => {
                                                Some(ordinary_storage::QueryExpression::Lte)
                                            }
                                            QueryExpression::Gt => {
                                                Some(ordinary_storage::QueryExpression::Gt)
                                            }
                                            QueryExpression::Lt => {
                                                Some(ordinary_storage::QueryExpression::Lt)
                                            }
                                            QueryExpression::Eq => {
                                                Some(ordinary_storage::QueryExpression::Eq)
                                            }
                                            QueryExpression::BeginsWith => {
                                                Some(ordinary_storage::QueryExpression::BeginsWith)
                                            }
                                        },
                                        None => None,
                                    };

                                    if let Some(idx) = auth_field_idx {
                                        queries.push((
                                            model_ref.idx,
                                            Query::Model(
                                                model_config.idx,
                                                config_field.idx,
                                                config_field.kind.clone(),
                                                ref_depth.clone(),
                                                exp,
                                            ),
                                            QueryKind::Token(idx),
                                            include_fields.clone(),
                                        ));
                                    } else {
                                        bail!("auth field {field} does not exist");
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        let mut cache_control = String::new();

        if let Some(cache) = &config.cache
            && let Some(http_cache) = &cache.http
            && let Some(http_cache_control) = &http_cache.cache_control
        {
            // todo: make the default configurable by the API server
            http_cache_control.header_value(&mut cache_control, "")?;
        } else {
            // todo: set a default for the cache control (dictated by Ordinary API Server)
        }

        let reporting_endpoints = format!(
            "csp=\"http{}://{domain}/.ordinary/reports/csp\"",
            if secure { "s" } else { "" }
        );

        Ok(Template {
            idx: config.idx,
            mime: HeaderValue::from_str(config.mime.as_str())?,
            reporting_endpoints: (
                REPORTING_ENDPOINTS,
                HeaderValue::from_str(reporting_endpoints.as_str())?,
            ),

            config,

            cache_control: if cache_control.is_empty() {
                None
            } else {
                Some(cache_control)
            },

            csp,

            engine,
            module,
            storage,

            globals,
            fields,

            queries: if queries.is_empty() {
                None
            } else {
                queries.sort_by_key(|a| a.0);
                let mut queries = queries
                    .iter()
                    .map(|(_, q, qk, i)| (q.clone(), qk.clone(), i.clone()))
                    .collect::<Vec<_>>();

                queries.shrink_to_fit();

                Some(queries)
            },
        })
    }

    pub fn start_tasks(&self) {
        if let Some(cache_config) = &self.config.cache
            && let Some(stored_cache) = &cache_config.stored
        {
            let storage_clone = self.storage.clone();

            let cache_config_clone = stored_cache.clone();
            let idx = self.config.idx;

            let template_span =
                info_span!("template", i = &self.config.idx, nm = %self.config.name);

            let cache_span = template_span.in_scope(|| info_span!("cache"));

            if let StoredCachePolicy::Permanent = stored_cache.policy {
                // don't start the cache_clean task
            } else {
                // todo: pass this default and a range check from Ordinary API
                let (mut clean_min, mut clean_max) =
                    cache_config_clone.clean_interval.unwrap_or((60, 60 * 3));

                clean_min *= 1000;
                clean_max *= 1000;

                tokio::spawn(async move {
                    loop {
                        // todo: break on app kill

                        let cache_clean_interval_ms = rand::random_range(clean_min..clean_max);

                        tokio::time::sleep(Duration::from_millis(cache_clean_interval_ms)).await;

                        async {
                            if let Err(err) = storage_clone
                                .cache
                                .clean_cache(&CacheRead::Template, &cache_config_clone, idx)
                                .await
                            {
                                tracing::error!(%err, "failed to clean cache");
                            }
                        }
                        .instrument(cache_span.clone())
                        .await;
                    }
                });
            }
        }
    }

    #[instrument(skip_all, err)]
    pub async fn set_wasm(
        &self,
        src: &[u8],
        app_config: &OrdinaryConfig,
        csp_style: Option<Vec<String>>,
        csp_script: Option<Vec<String>>,
        secure: bool,
    ) -> anyhow::Result<()> {
        let storage_span = info_span!("storage");
        let span = storage_span.in_scope(|| info_span!("artifact"));

        #[cfg(feature = "studio")]
        let script_urls = Some(vec![IFRAME_RESIZER_CHILD_URL.to_string()]);

        #[cfg(not(feature = "studio"))]
        let script_urls = None;

        let csp_string = self.config.csp.clone().unwrap_or_default().build_string(
            &app_config.csp.clone().unwrap_or_default(),
            csp_style,
            csp_script,
            script_urls,
            secure,
            app_config.has_ordinary_actions() || app_config.auth.is_some(),
        );

        let mut builder = flexbuffers::Builder::new(&flexbuffers::BuilderOptions::SHARE_NONE);
        let mut builder_vec = builder.start_vector();

        builder_vec.push(csp_string.as_str());
        builder_vec.push(flexbuffers::Blob(src));

        builder_vec.end_vector();

        span.in_scope(|| {
            self.storage
                .artifact
                .put(self.idx, ArtifactKind::Template, builder.view())
        })?;

        {
            let mut lock = self.module.write();
            let module = Module::new(&self.engine, src)?;

            *lock = Some(module);
        }

        if let Ok(mime) = self.mime.to_str()
            && matches!(mime, "text/html" | "text/html; charset=utf-8" | "text/xml")
        {
            let mut lock = self.csp.write();

            *lock = Some(HeaderValue::from_str(csp_string.as_str())?);
            drop(lock);
        }

        let span = storage_span.in_scope(|| info_span!("cache"));

        async {
            self.storage
                .cache
                .artifact_evict(CacheRead::Template, self.idx)
                .await
        }
        .instrument(span)
        .await?;

        Ok(())
    }

    #[instrument(skip_all, err)]
    pub fn render(
        &self,
        host: &str,
        path: String,
        params: Option<String>,
        // message and code
        error: Option<(String, u16)>,
        // svg qr_code, account and recovery_codes
        totp: Option<(String, String, String)>,
        claims: &Option<VectorReader<&[u8]>>,
    ) -> anyhow::Result<TemplateResult> {
        let args = self.query(host, path, params, error, totp, claims)?;

        match self.config.ffi.version {
            TemplateFfiVersion::V1 => {
                #[cfg(not(feature = "studio"))]
                {
                    ffi::v1::call(self, &args)
                }

                #[cfg(feature = "studio")]
                {
                    if self.config.mime.contains("html") {
                        let res = ffi::v1::call(self, &args)?;

                        match res {
                            TemplateResult::StatusCode(_) => Ok(res),
                            TemplateResult::Result(bytes) => {
                                let str = std::str::from_utf8(bytes.as_ref())?;

                                let res = if str.contains("<head>") {
                                    str.replace("<head>", &format!(r#"<head><script async src="{IFRAME_RESIZER_CHILD_URL}"></script>"#))
                                } else {
                                    str.replace("<html lang=en>", &format!(r#"<html lang=en><script async src="{IFRAME_RESIZER_CHILD_URL}"></script>"#))
                                };

                                Ok(TemplateResult::Result(Bytes::copy_from_slice(
                                    res.as_bytes(),
                                )))
                            }
                        }
                    } else {
                        ffi::v1::call(self, &args)
                    }
                }
            }
        }
    }

    // accepts token + bound arguments and then uses config to go request all the stuff
    #[allow(clippy::too_many_lines)]
    #[instrument(skip_all, err)]
    pub fn query(
        &self,
        host: &str,
        path: String,
        params: Option<String>,
        // message and code
        error: Option<(String, u16)>,
        // svg qr_code, account and recovery_codes
        totp: Option<(String, String, String)>,
        claims: &Option<VectorReader<&[u8]>>,
    ) -> anyhow::Result<Bytes> {
        let mut builder = flexbuffers::Builder::new(&flexbuffers::BuilderOptions::SHARE_NONE);
        let mut vec_builder = builder.start_vector();

        if let Some(queries) = &self.queries {
            let segments: Vec<&str> = path.split('/').collect();

            let _params_map = match params {
                Some(_params) => {
                    let params_map: BTreeMap<String, String> = BTreeMap::new();
                    // todo: update params map
                    Some(params_map)
                }
                None => None,
            };

            // todo: push params into

            // todo: push flags into

            for (query, query_kind, includes) in queries {
                let kind = match query {
                    Query::Model(_, _, kind, _, _) | Query::Content(_, _, kind) => kind,
                    Query::ContentMulti(_) => &Kind::Void,
                };

                let indexed_val: Bytes = match query_kind {
                    QueryKind::Segment(pos, is_wildcard) => {
                        if pos <= &segments.len() {
                            let val = if *is_wildcard {
                                let mut out = String::new();

                                for (i, segment) in segments.iter().enumerate() {
                                    if i == *pos {
                                        (*segment).clone_into(&mut out);
                                    } else if i > *pos {
                                        out = format!("{out}/{segment}");
                                    }
                                }

                                out
                            } else {
                                segments[*pos].to_string()
                            };

                            match kind {
                                Kind::Uuid => {
                                    let uuid = uuid::Uuid::from_str(&val)?;
                                    Bytes::copy_from_slice(uuid.as_bytes())
                                }
                                _ => Bytes::copy_from_slice(val.as_bytes()),
                            }
                        } else {
                            bail!("position out of bounds for route");
                        }
                    }
                    QueryKind::Token(field_idx) => {
                        if let Some(claims) = claims {
                            let reader = claims.idx(*field_idx as usize);

                            match kind {
                                Kind::Uuid => Bytes::copy_from_slice(reader.as_blob().0),
                                Kind::String => Bytes::copy_from_slice(reader.as_str().as_bytes()),
                                _ => Bytes::new(),
                            }
                        } else {
                            bail!("no claims on query");
                        }
                    }
                    QueryKind::None => Bytes::new(),
                };

                let span = info_span!("storage");

                match query {
                    Query::Content(def_idx, field_idx, _kind) => {
                        let content_obj = span.in_scope(|| {
                            let content_span = info_span!("content");

                            content_span.in_scope(|| {
                                self.storage.content.get(*def_idx, *field_idx, &indexed_val)
                            })
                        })?;

                        let root = flexbuffers::Reader::get_root(&content_obj[..])?;

                        let mut fields_builder = vec_builder.start_vector();

                        for include in includes {
                            include.marry(&mut fields_builder, &root.as_vector())?;
                        }

                        fields_builder.end_vector();
                    }
                    Query::ContentMulti(def_idx) => {
                        let content_objs = span.in_scope(|| {
                            let content_span = info_span!("content");

                            content_span.in_scope(|| self.storage.content.list(*def_idx))
                        })?;

                        let root = flexbuffers::Reader::get_root(&content_objs[..])?;

                        let mut object_vector = vec_builder.start_vector();

                        for object in &root.as_vector() {
                            let obj_bytes = object.as_blob().0;

                            let object = flexbuffers::Reader::get_root(obj_bytes)?;

                            let mut fields_builder = object_vector.start_vector();

                            for include in includes {
                                include.marry(&mut fields_builder, &object.as_vector())?;
                            }

                            fields_builder.end_vector();
                        }

                        object_vector.end_vector();
                    }
                    Query::Model(model_kind, field_idx, _kind, ref_depth, expression) => {
                        if let Some(exp) = expression {
                            let items = span.in_scope(|| {
                                self.storage.model.query_model(
                                    *model_kind,
                                    *field_idx,
                                    exp.as_byte(),
                                    &indexed_val,
                                    ref_depth,
                                    None,
                                )
                            })?;

                            let root = flexbuffers::Reader::get_root(&items[..])?;

                            let mut item_builder = vec_builder.start_vector();

                            for item in &root.as_vector() {
                                let mut fields_builder = item_builder.start_vector();

                                for include in includes {
                                    include.marry(&mut fields_builder, &item.as_vector())?;
                                }

                                fields_builder.end_vector();
                            }

                            item_builder.end_vector();
                        } else {
                            let model_item = span.in_scope(|| {
                                self.storage.model.get_model(
                                    *model_kind,
                                    *field_idx,
                                    &indexed_val,
                                    ref_depth,
                                    None,
                                )
                            })?;

                            let root = flexbuffers::Reader::get_root(&model_item[..])?;

                            let mut fields_builder = vec_builder.start_vector();

                            for include in includes {
                                include.marry(&mut fields_builder, &root.as_vector())?;
                            }

                            fields_builder.end_vector();
                        }
                    }
                }
            }
        }

        if let Some(error) = error {
            let mut error_builder = vec_builder.start_vector();

            error_builder.push(error.0.as_str());
            error_builder.push(error.1);

            error_builder.end_vector();
        }

        if let Some(totp) = totp {
            let mut totp_builder = vec_builder.start_vector();

            totp_builder.push(totp.0.as_str());
            totp_builder.push(totp.1.as_str());

            let mut recovery_codes_vec = totp_builder.start_vector();

            let mut chunk = String::new();

            for (i, c) in totp.2.chars().enumerate() {
                if i != 0 && i % 11 == 0 {
                    recovery_codes_vec.push(chunk.as_str());
                    chunk = String::new();
                } else {
                    chunk = format!("{chunk}{c}");
                }
            }

            recovery_codes_vec.end_vector();

            totp_builder.end_vector();
        }

        vec_builder.push(host);

        if let Some(globals) = &self.globals {
            vec_builder.push(flexbuffers::Blob(globals.as_ref()));
        }
        if let Some(fields) = &self.fields {
            vec_builder.push(flexbuffers::Blob(fields.as_ref()));
        }

        vec_builder.end_vector();

        Ok(Bytes::copy_from_slice(builder.view()))
    }
}
