// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: org.farmapps.temp.agroconnect.cl022
//
// This file was automatically generated from Lexicon schemas.
// Any manual changes will be overwritten on the next regeneration.

#[allow(unused_imports)]
use alloc::collections::BTreeMap;

#[allow(unused_imports)]
use core::marker::PhantomData;
use jacquard_common::CowStr;

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
use jacquard_common::types::collection::{Collection, RecordError};
use jacquard_common::types::string::{AtUri, Cid, Datetime};
use jacquard_common::types::uri::{RecordUri, UriError};
use jacquard_common::xrpc::XrpcResp;
use jacquard_derive::{IntoStatic, lexicon};
use jacquard_lexicon::lexicon::LexiconDoc;
use jacquard_lexicon::schema::LexiconSchema;

#[allow(unused_imports)]
use jacquard_lexicon::validation::{ConstraintError, ValidationPath};
use serde::{Serialize, Deserialize};
use crate::org_farmapps::temp::ecrop::CodeType;
/// Fertilizer codelist

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Cl022<'a> {
    ///Date when added to the list
    #[serde(skip_serializing_if = "Option::is_none")]
    pub added: Option<Datetime>,
    ///Comment
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub comment: Option<CowStr<'a>>,
    ///Denominator used for all fertilizer content properties
    #[serde(skip_serializing_if = "Option::is_none")]
    pub denominator: Option<i64>,
    ///Description / name of the fertilizer
    #[serde(borrow)]
    pub description: CowStr<'a>,
    ///Id off the fertilizer
    #[serde(borrow)]
    pub id: CodeType<'a>,
    ///<unit> Potassium oxide content of this fertilizer
    #[serde(skip_serializing_if = "Option::is_none")]
    pub k2o: Option<i64>,
    ///<unit> Nitrogen content of this fertilizer
    #[serde(skip_serializing_if = "Option::is_none")]
    pub n: Option<i64>,
    ///<unit> Phosphate content of this fertilizer
    #[serde(skip_serializing_if = "Option::is_none")]
    pub p2o5: Option<i64>,
    ///Fertlizer type
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub r#type: Option<CowStr<'a>>,
    ///Unit
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub unit: Option<CowStr<'a>>,
    ///Date when updated
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated: Option<Datetime>,
}

/// Typed wrapper for GetRecord response with this collection's record type.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Cl022GetRecordOutput<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub cid: Option<Cid<'a>>,
    #[serde(borrow)]
    pub uri: AtUri<'a>,
    #[serde(borrow)]
    pub value: Cl022<'a>,
}

impl<'a> Cl022<'a> {
    pub fn uri(
        uri: impl Into<CowStr<'a>>,
    ) -> Result<RecordUri<'a, Cl022Record>, UriError> {
        RecordUri::try_from_uri(AtUri::new_cow(uri.into())?)
    }
}

/// Marker type for deserializing records from this collection.

#[derive(Debug, Serialize, Deserialize)]
pub struct Cl022Record;
impl XrpcResp for Cl022Record {
    const NSID: &'static str = "org.farmapps.temp.agroconnect.cl022";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = Cl022GetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

impl From<Cl022GetRecordOutput<'_>> for Cl022<'_> {
    fn from(output: Cl022GetRecordOutput<'_>) -> Self {
        use jacquard_common::IntoStatic;
        output.value.into_static()
    }
}

impl Collection for Cl022<'_> {
    const NSID: &'static str = "org.farmapps.temp.agroconnect.cl022";
    type Record = Cl022Record;
}

impl Collection for Cl022Record {
    const NSID: &'static str = "org.farmapps.temp.agroconnect.cl022";
    type Record = Cl022Record;
}

impl<'a> LexiconSchema for Cl022<'a> {
    fn nsid() -> &'static str {
        "org.farmapps.temp.agroconnect.cl022"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_org_farmapps_temp_agroconnect_cl022()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.denominator {
            if *value < 1i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("denominator"),
                    min: 1i64,
                    actual: *value,
                });
            }
        }
        if let Some(ref value) = self.k2o {
            if *value < 0i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("k2o"),
                    min: 0i64,
                    actual: *value,
                });
            }
        }
        if let Some(ref value) = self.n {
            if *value < 0i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("n"),
                    min: 0i64,
                    actual: *value,
                });
            }
        }
        if let Some(ref value) = self.p2o5 {
            if *value < 0i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("p2o5"),
                    min: 0i64,
                    actual: *value,
                });
            }
        }
        Ok(())
    }
}

pub mod cl022_state {

    pub use crate::builder_types::{Set, Unset, IsSet, IsUnset};
    #[allow(unused)]
    use ::core::marker::PhantomData;
    mod sealed {
        pub trait Sealed {}
    }
    /// State trait tracking which required fields have been set
    pub trait State: sealed::Sealed {
        type Id;
        type Description;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Id = Unset;
        type Description = Unset;
    }
    ///State transition - sets the `id` field to Set
    pub struct SetId<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetId<S> {}
    impl<S: State> State for SetId<S> {
        type Id = Set<members::id>;
        type Description = S::Description;
    }
    ///State transition - sets the `description` field to Set
    pub struct SetDescription<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetDescription<S> {}
    impl<S: State> State for SetDescription<S> {
        type Id = S::Id;
        type Description = Set<members::description>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `id` field
        pub struct id(());
        ///Marker type for the `description` field
        pub struct description(());
    }
}

/// Builder for constructing an instance of this type
pub struct Cl022Builder<'a, S: cl022_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Datetime>,
        Option<CowStr<'a>>,
        Option<i64>,
        Option<CowStr<'a>>,
        Option<CodeType<'a>>,
        Option<i64>,
        Option<i64>,
        Option<i64>,
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
        Option<Datetime>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Cl022<'a> {
    /// Create a new builder for this type
    pub fn new() -> Cl022Builder<'a, cl022_state::Empty> {
        Cl022Builder::new()
    }
}

impl<'a> Cl022Builder<'a, cl022_state::Empty> {
    /// Create a new builder with all fields unset
    pub fn new() -> Self {
        Cl022Builder {
            _state: PhantomData,
            _fields: (None, None, None, None, None, None, None, None, None, None, None),
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: cl022_state::State> Cl022Builder<'a, S> {
    /// Set the `added` field (optional)
    pub fn added(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `added` field to an Option value (optional)
    pub fn maybe_added(mut self, value: Option<Datetime>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<'a, S: cl022_state::State> Cl022Builder<'a, S> {
    /// Set the `comment` field (optional)
    pub fn comment(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `comment` field to an Option value (optional)
    pub fn maybe_comment(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<'a, S: cl022_state::State> Cl022Builder<'a, S> {
    /// Set the `denominator` field (optional)
    pub fn denominator(mut self, value: impl Into<Option<i64>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `denominator` field to an Option value (optional)
    pub fn maybe_denominator(mut self, value: Option<i64>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<'a, S> Cl022Builder<'a, S>
where
    S: cl022_state::State,
    S::Description: cl022_state::IsUnset,
{
    /// Set the `description` field (required)
    pub fn description(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> Cl022Builder<'a, cl022_state::SetDescription<S>> {
        self._fields.3 = Option::Some(value.into());
        Cl022Builder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> Cl022Builder<'a, S>
where
    S: cl022_state::State,
    S::Id: cl022_state::IsUnset,
{
    /// Set the `id` field (required)
    pub fn id(
        mut self,
        value: impl Into<CodeType<'a>>,
    ) -> Cl022Builder<'a, cl022_state::SetId<S>> {
        self._fields.4 = Option::Some(value.into());
        Cl022Builder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: cl022_state::State> Cl022Builder<'a, S> {
    /// Set the `k2o` field (optional)
    pub fn k2o(mut self, value: impl Into<Option<i64>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `k2o` field to an Option value (optional)
    pub fn maybe_k2o(mut self, value: Option<i64>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<'a, S: cl022_state::State> Cl022Builder<'a, S> {
    /// Set the `n` field (optional)
    pub fn n(mut self, value: impl Into<Option<i64>>) -> Self {
        self._fields.6 = value.into();
        self
    }
    /// Set the `n` field to an Option value (optional)
    pub fn maybe_n(mut self, value: Option<i64>) -> Self {
        self._fields.6 = value;
        self
    }
}

impl<'a, S: cl022_state::State> Cl022Builder<'a, S> {
    /// Set the `p2o5` field (optional)
    pub fn p2o5(mut self, value: impl Into<Option<i64>>) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `p2o5` field to an Option value (optional)
    pub fn maybe_p2o5(mut self, value: Option<i64>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<'a, S: cl022_state::State> Cl022Builder<'a, S> {
    /// Set the `type` field (optional)
    pub fn r#type(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.8 = value.into();
        self
    }
    /// Set the `type` field to an Option value (optional)
    pub fn maybe_type(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.8 = value;
        self
    }
}

impl<'a, S: cl022_state::State> Cl022Builder<'a, S> {
    /// Set the `unit` field (optional)
    pub fn unit(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.9 = value.into();
        self
    }
    /// Set the `unit` field to an Option value (optional)
    pub fn maybe_unit(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.9 = value;
        self
    }
}

impl<'a, S: cl022_state::State> Cl022Builder<'a, S> {
    /// Set the `updated` field (optional)
    pub fn updated(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.10 = value.into();
        self
    }
    /// Set the `updated` field to an Option value (optional)
    pub fn maybe_updated(mut self, value: Option<Datetime>) -> Self {
        self._fields.10 = value;
        self
    }
}

impl<'a, S> Cl022Builder<'a, S>
where
    S: cl022_state::State,
    S::Id: cl022_state::IsSet,
    S::Description: cl022_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Cl022<'a> {
        Cl022 {
            added: self._fields.0,
            comment: self._fields.1,
            denominator: self._fields.2,
            description: self._fields.3.unwrap(),
            id: self._fields.4.unwrap(),
            k2o: self._fields.5,
            n: self._fields.6,
            p2o5: self._fields.7,
            r#type: self._fields.8,
            unit: self._fields.9,
            updated: self._fields.10,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data
    pub fn build_with_data(
        self,
        extra_data: BTreeMap<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Cl022<'a> {
        Cl022 {
            added: self._fields.0,
            comment: self._fields.1,
            denominator: self._fields.2,
            description: self._fields.3.unwrap(),
            id: self._fields.4.unwrap(),
            k2o: self._fields.5,
            n: self._fields.6,
            p2o5: self._fields.7,
            r#type: self._fields.8,
            unit: self._fields.9,
            updated: self._fields.10,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_org_farmapps_temp_agroconnect_cl022() -> LexiconDoc<'static> {
    #[allow(unused_imports)]
    use jacquard_common::{CowStr, deps::smol_str::SmolStr, types::blob::MimeType};
    use jacquard_lexicon::lexicon::*;
    use alloc::collections::BTreeMap;
    LexiconDoc {
        lexicon: Lexicon::Lexicon1,
        id: CowStr::new_static("org.farmapps.temp.agroconnect.cl022"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(CowStr::new_static("Fertilizer codelist")),
                    key: Some(CowStr::new_static("any")),
                    record: LexRecordRecord::Object(LexObject {
                        description: Some(CowStr::new_static("Codelist ferilizers")),
                        required: Some(
                            vec![
                                SmolStr::new_static("id"),
                                SmolStr::new_static("description")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("added"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Date when added to the list"),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("comment"),
                                LexObjectProperty::String(LexString {
                                    description: Some(CowStr::new_static("Comment")),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("denominator"),
                                LexObjectProperty::Integer(LexInteger {
                                    minimum: Some(1i64),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("description"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Description / name of the fertilizer"),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("id"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static(
                                        "org.farmapps.temp.ecrop.defs#codeType",
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("k2o"),
                                LexObjectProperty::Integer(LexInteger {
                                    minimum: Some(0i64),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("n"),
                                LexObjectProperty::Integer(LexInteger {
                                    minimum: Some(0i64),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("p2o5"),
                                LexObjectProperty::Integer(LexInteger {
                                    minimum: Some(0i64),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("type"),
                                LexObjectProperty::String(LexString {
                                    description: Some(CowStr::new_static("Fertlizer type")),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("unit"),
                                LexObjectProperty::String(LexString {
                                    description: Some(CowStr::new_static("Unit ")),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("updated"),
                                LexObjectProperty::String(LexString {
                                    description: Some(CowStr::new_static("Date when updated")),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}