// @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, BosStr, DefaultStr, FromStaticStr};

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
use jacquard_common::deps::smol_str::SmolStr;
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::types::value::Data;
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

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "org.farmapps.temp.agroconnect.cl022",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Cl022<S: BosStr = DefaultStr> {
    ///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")]
    pub comment: Option<S>,
    ///Denominator used for all fertilizer content properties
    #[serde(skip_serializing_if = "Option::is_none")]
    pub denominator: Option<i64>,
    ///Description / name of the fertilizer
    pub description: S,
    ///Id off the fertilizer
    pub id: CodeType<S>,
    ///<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")]
    pub r#type: Option<S>,
    ///Unit
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unit: Option<S>,
    ///Date when updated
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated: Option<Datetime>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// 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<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Cl022<S>,
}

impl<S: BosStr> Cl022<S> {
    pub fn uri(uri: S) -> Result<RecordUri<S, Cl022Record>, UriError> {
        RecordUri::try_from_uri(AtUri::new(uri)?)
    }
}

/// 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<S: BosStr> = Cl022GetRecordOutput<S>;
    type Err = RecordError;
}

impl<S: BosStr> From<Cl022GetRecordOutput<S>> for Cl022<S> {
    fn from(output: Cl022GetRecordOutput<S>) -> Self {
        output.value
    }
}

impl<S: BosStr> Collection for Cl022<S> {
    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<S: BosStr> LexiconSchema for Cl022<S> {
    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 Description;
        type Id;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Description = Unset;
        type Id = Unset;
    }
    ///State transition - sets the `description` field to Set
    pub struct SetDescription<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetDescription<St> {}
    impl<St: State> State for SetDescription<St> {
        type Description = Set<members::description>;
        type Id = St::Id;
    }
    ///State transition - sets the `id` field to Set
    pub struct SetId<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetId<St> {}
    impl<St: State> State for SetId<St> {
        type Description = St::Description;
        type Id = Set<members::id>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `description` field
        pub struct description(());
        ///Marker type for the `id` field
        pub struct id(());
    }
}

/// Builder for constructing an instance of this type.
pub struct Cl022Builder<St: cl022_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Datetime>,
        Option<S>,
        Option<i64>,
        Option<S>,
        Option<CodeType<S>>,
        Option<i64>,
        Option<i64>,
        Option<i64>,
        Option<S>,
        Option<S>,
        Option<Datetime>,
    ),
    _type: PhantomData<fn() -> S>,
}

impl Cl022<DefaultStr> {
    /// Create a new builder for this type, using the default string type (DefaultStr = SmolStr) if needed
    pub fn new() -> Cl022Builder<cl022_state::Empty, DefaultStr> {
        Cl022Builder::new()
    }
}

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

impl Cl022Builder<cl022_state::Empty, DefaultStr> {
    /// Create a new builder with all fields unset, using the default string type, if needed
    pub fn new() -> Self {
        Cl022Builder {
            _state: PhantomData,
            _fields: (None, None, None, None, None, None, None, None, None, None, None),
            _type: PhantomData,
        }
    }
}

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

impl<St: cl022_state::State, S: BosStr> Cl022Builder<St, 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<St: cl022_state::State, S: BosStr> Cl022Builder<St, S> {
    /// Set the `comment` field (optional)
    pub fn comment(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `comment` field to an Option value (optional)
    pub fn maybe_comment(mut self, value: Option<S>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<St: cl022_state::State, S: BosStr> Cl022Builder<St, 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<St, S: BosStr> Cl022Builder<St, S>
where
    St: cl022_state::State,
    St::Description: cl022_state::IsUnset,
{
    /// Set the `description` field (required)
    pub fn description(
        mut self,
        value: impl Into<S>,
    ) -> Cl022Builder<cl022_state::SetDescription<St>, S> {
        self._fields.3 = Option::Some(value.into());
        Cl022Builder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

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

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

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

impl<St: cl022_state::State, S: BosStr> Cl022Builder<St, 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<St, S: BosStr> Cl022Builder<St, S>
where
    St: cl022_state::State,
    St::Description: cl022_state::IsSet,
    St::Id: cl022_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Cl022<S> {
        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<SmolStr, Data<S>>) -> Cl022<S> {
        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()
    }
}