// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: blue.recipes.feed.recipe
//
// 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::blob::BlobRef;
use jacquard_common::types::collection::{Collection, RecordError};
use jacquard_common::types::string::{AtUri, Cid};
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::blue_recipes::feed::recipe;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Ingredient<S: BosStr = DefaultStr> {
    ///The amount of the ingredient needed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub amount: Option<S>,
    ///The name of the ingredient.
    pub name: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// Record containing a recipe.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "blue.recipes.feed.recipe",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Recipe<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<S>,
    ///Free-form recipe description text.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<S>,
    ///Image representing the recipe.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image: Option<BlobRef<S>>,
    pub ingredients: Vec<recipe::Ingredient<S>>,
    ///The number of servings the recipe prepares.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub serves: Option<i64>,
    pub steps: Vec<recipe::Step<S>>,
    ///The amount of time (in minutes) it takes to complete the recipe.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time: Option<i64>,
    pub title: S,
    #[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 RecipeGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Recipe<S>,
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Step<S: BosStr = DefaultStr> {
    ///The instruction to provide to the user.
    pub text: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

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

impl<S: BosStr> LexiconSchema for Ingredient<S> {
    fn nsid() -> &'static str {
        "blue.recipes.feed.recipe"
    }
    fn def_name() -> &'static str {
        "ingredient"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_blue_recipes_feed_recipe()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.name;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 3000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("name"),
                    max: 3000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.name;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 300usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("name"),
                        max: 300usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

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

#[derive(Debug, Serialize, Deserialize)]
pub struct RecipeRecord;
impl XrpcResp for RecipeRecord {
    const NSID: &'static str = "blue.recipes.feed.recipe";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = RecipeGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Recipe<S> {
    const NSID: &'static str = "blue.recipes.feed.recipe";
    type Record = RecipeRecord;
}

impl Collection for RecipeRecord {
    const NSID: &'static str = "blue.recipes.feed.recipe";
    type Record = RecipeRecord;
}

impl<S: BosStr> LexiconSchema for Recipe<S> {
    fn nsid() -> &'static str {
        "blue.recipes.feed.recipe"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_blue_recipes_feed_recipe()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.description {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 3000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("description"),
                    max: 3000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.description {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 300usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("description"),
                        max: 300usize,
                        actual: count,
                    });
                }
            }
        }
        if let Some(ref value) = self.image {
            {
                let size = value.blob().size;
                if size > 1000000usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("image"),
                        max: 1000000usize,
                        actual: size,
                    });
                }
            }
        }
        if let Some(ref value) = self.image {
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &["image/png", "image/jpeg"];
                let matched = accepted
                    .iter()
                    .any(|pattern| {
                        if *pattern == "*/*" {
                            true
                        } else if pattern.ends_with("/*") {
                            let prefix = &pattern[..pattern.len() - 2];
                            mime.starts_with(prefix)
                                && mime.as_bytes().get(prefix.len()) == Some(&b'/')
                        } else {
                            mime == *pattern
                        }
                    });
                if !matched {
                    return Err(ConstraintError::BlobMimeTypeNotAccepted {
                        path: ValidationPath::from_field("image"),
                        accepted: vec![
                            "image/png".to_string(), "image/jpeg".to_string()
                        ],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        {
            let value = &self.title;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 3000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("title"),
                    max: 3000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.title;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 300usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("title"),
                        max: 300usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for Step<S> {
    fn nsid() -> &'static str {
        "blue.recipes.feed.recipe"
    }
    fn def_name() -> &'static str {
        "step"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_blue_recipes_feed_recipe()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.text;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 5000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("text"),
                    max: 5000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.text;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 500usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("text"),
                        max: 500usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

fn lexicon_doc_blue_recipes_feed_recipe() -> 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("blue.recipes.feed.recipe"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("ingredient"),
                LexUserType::Object(LexObject {
                    required: Some(vec![SmolStr::new_static("name")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("amount"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("The amount of the ingredient needed."),
                                ),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("name"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("The name of the ingredient."),
                                ),
                                max_length: Some(3000usize),
                                max_graphemes: Some(300usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(CowStr::new_static("Record containing a recipe.")),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("title"), SmolStr::new_static("steps"),
                                SmolStr::new_static("ingredients")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("description"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Free-form recipe description text."),
                                    ),
                                    max_length: Some(3000usize),
                                    max_graphemes: Some(300usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("image"),
                                LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                            );
                            map.insert(
                                SmolStr::new_static("ingredients"),
                                LexObjectProperty::Array(LexArray {
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#ingredient"),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("serves"),
                                LexObjectProperty::Integer(LexInteger {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("steps"),
                                LexObjectProperty::Array(LexArray {
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#step"),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("time"),
                                LexObjectProperty::Integer(LexInteger {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("title"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(3000usize),
                                    max_graphemes: Some(300usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("step"),
                LexUserType::Object(LexObject {
                    required: Some(vec![SmolStr::new_static("text")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("text"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "The instruction to provide to the user.",
                                    ),
                                ),
                                max_length: Some(5000usize),
                                max_graphemes: Some(500usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod recipe_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 Ingredients;
        type Steps;
        type Title;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Ingredients = Unset;
        type Steps = Unset;
        type Title = Unset;
    }
    ///State transition - sets the `ingredients` field to Set
    pub struct SetIngredients<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetIngredients<St> {}
    impl<St: State> State for SetIngredients<St> {
        type Ingredients = Set<members::ingredients>;
        type Steps = St::Steps;
        type Title = St::Title;
    }
    ///State transition - sets the `steps` field to Set
    pub struct SetSteps<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetSteps<St> {}
    impl<St: State> State for SetSteps<St> {
        type Ingredients = St::Ingredients;
        type Steps = Set<members::steps>;
        type Title = St::Title;
    }
    ///State transition - sets the `title` field to Set
    pub struct SetTitle<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetTitle<St> {}
    impl<St: State> State for SetTitle<St> {
        type Ingredients = St::Ingredients;
        type Steps = St::Steps;
        type Title = Set<members::title>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `ingredients` field
        pub struct ingredients(());
        ///Marker type for the `steps` field
        pub struct steps(());
        ///Marker type for the `title` field
        pub struct title(());
    }
}

/// Builder for constructing an instance of this type.
pub struct RecipeBuilder<St: recipe_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<S>,
        Option<S>,
        Option<BlobRef<S>>,
        Option<Vec<recipe::Ingredient<S>>>,
        Option<i64>,
        Option<Vec<recipe::Step<S>>>,
        Option<i64>,
        Option<S>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> Recipe<S> {
    /// Create a new builder for this type
    pub fn builder() -> RecipeBuilder<recipe_state::Empty, S> {
        RecipeBuilder::builder()
    }
}

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

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

impl<St: recipe_state::State, S: BosStr> RecipeBuilder<St, S> {
    /// Set the `createdAt` field (optional)
    pub fn created_at(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `createdAt` field to an Option value (optional)
    pub fn maybe_created_at(mut self, value: Option<S>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St: recipe_state::State, S: BosStr> RecipeBuilder<St, S> {
    /// Set the `description` field (optional)
    pub fn description(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `description` field to an Option value (optional)
    pub fn maybe_description(mut self, value: Option<S>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<St: recipe_state::State, S: BosStr> RecipeBuilder<St, S> {
    /// Set the `image` field (optional)
    pub fn image(mut self, value: impl Into<Option<BlobRef<S>>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `image` field to an Option value (optional)
    pub fn maybe_image(mut self, value: Option<BlobRef<S>>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<St, S: BosStr> RecipeBuilder<St, S>
where
    St: recipe_state::State,
    St::Ingredients: recipe_state::IsUnset,
{
    /// Set the `ingredients` field (required)
    pub fn ingredients(
        mut self,
        value: impl Into<Vec<recipe::Ingredient<S>>>,
    ) -> RecipeBuilder<recipe_state::SetIngredients<St>, S> {
        self._fields.3 = Option::Some(value.into());
        RecipeBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: recipe_state::State, S: BosStr> RecipeBuilder<St, S> {
    /// Set the `serves` field (optional)
    pub fn serves(mut self, value: impl Into<Option<i64>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `serves` field to an Option value (optional)
    pub fn maybe_serves(mut self, value: Option<i64>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St, S: BosStr> RecipeBuilder<St, S>
where
    St: recipe_state::State,
    St::Steps: recipe_state::IsUnset,
{
    /// Set the `steps` field (required)
    pub fn steps(
        mut self,
        value: impl Into<Vec<recipe::Step<S>>>,
    ) -> RecipeBuilder<recipe_state::SetSteps<St>, S> {
        self._fields.5 = Option::Some(value.into());
        RecipeBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: recipe_state::State, S: BosStr> RecipeBuilder<St, S> {
    /// Set the `time` field (optional)
    pub fn time(mut self, value: impl Into<Option<i64>>) -> Self {
        self._fields.6 = value.into();
        self
    }
    /// Set the `time` field to an Option value (optional)
    pub fn maybe_time(mut self, value: Option<i64>) -> Self {
        self._fields.6 = value;
        self
    }
}

impl<St, S: BosStr> RecipeBuilder<St, S>
where
    St: recipe_state::State,
    St::Title: recipe_state::IsUnset,
{
    /// Set the `title` field (required)
    pub fn title(
        mut self,
        value: impl Into<S>,
    ) -> RecipeBuilder<recipe_state::SetTitle<St>, S> {
        self._fields.7 = Option::Some(value.into());
        RecipeBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> RecipeBuilder<St, S>
where
    St: recipe_state::State,
    St::Ingredients: recipe_state::IsSet,
    St::Steps: recipe_state::IsSet,
    St::Title: recipe_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Recipe<S> {
        Recipe {
            created_at: self._fields.0,
            description: self._fields.1,
            image: self._fields.2,
            ingredients: self._fields.3.unwrap(),
            serves: self._fields.4,
            steps: self._fields.5.unwrap(),
            time: self._fields.6,
            title: self._fields.7.unwrap(),
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(self, extra_data: BTreeMap<SmolStr, Data<S>>) -> Recipe<S> {
        Recipe {
            created_at: self._fields.0,
            description: self._fields.1,
            image: self._fields.2,
            ingredients: self._fields.3.unwrap(),
            serves: self._fields.4,
            steps: self._fields.5.unwrap(),
            time: self._fields.6,
            title: self._fields.7.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}