//! Helper functions for struct code generation

use proc_macro2::TokenStream;
use quote::quote;

use crate::ir::FieldDefinition;

pub(crate) use crate::codegen::helpers::generate_field_key;

/// Generate field value for JSON/GraphQL with a config-resolved key.
/// Returns `Option<(&str, Value)>` - None if the field is Option and value is None.
pub(super) fn generate_field_value(field: &FieldDefinition) -> TokenStream {
    let private = quote!(::apollo_errors::private);
    let serde_json_crate = quote!(#private::serde_json);

    let rust_name = &field.rust_name;
    let field_key = generate_field_key(field);

    if field.is_option {
        quote! {
            self.#rust_name.as_ref().map(|__apollo_inner| {
                (#field_key, #serde_json_crate::to_value(__apollo_inner).unwrap_or(#serde_json_crate::Value::Null))
            })
        }
    } else {
        quote! {
            ::std::option::Option::Some((#field_key, #serde_json_crate::to_value(&self.#rust_name).unwrap_or(#serde_json_crate::Value::Null)))
        }
    }
}
