// @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;

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

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct Ingredient<'a> {
    ///The amount of the ingredient needed.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub amount: Option<CowStr<'a>>,
    ///The name of the ingredient.
    #[serde(borrow)]
    pub name: CowStr<'a>,
}

/// Record containing a recipe.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Recipe<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub created_at: Option<CowStr<'a>>,
    ///Free-form recipe description text.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub description: Option<CowStr<'a>>,
    ///Image representing the recipe.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub image: Option<BlobRef<'a>>,
    #[serde(borrow)]
    pub ingredients: Vec<recipe::Ingredient<'a>>,
    ///The number of servings the recipe prepares.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub serves: Option<i64>,
    #[serde(borrow)]
    pub steps: Vec<recipe::Step<'a>>,
    ///The amount of time (in minutes) it takes to complete the recipe.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time: Option<i64>,
    #[serde(borrow)]
    pub title: CowStr<'a>,
}

/// 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<'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: Recipe<'a>,
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct Step<'a> {
    ///The instruction to provide to the user.
    #[serde(borrow)]
    pub text: CowStr<'a>,
}

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

impl<'a> LexiconSchema for Ingredient<'a> {
    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<'de> = RecipeGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

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

/// Builder for constructing an instance of this type
pub struct RecipeBuilder<'a, S: recipe_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
        Option<BlobRef<'a>>,
        Option<Vec<recipe::Ingredient<'a>>>,
        Option<i64>,
        Option<Vec<recipe::Step<'a>>>,
        Option<i64>,
        Option<CowStr<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

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

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

impl<'a, S: recipe_state::State> RecipeBuilder<'a, S> {
    /// Set the `createdAt` field (optional)
    pub fn created_at(mut self, value: impl Into<Option<CowStr<'a>>>) -> 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<CowStr<'a>>) -> Self {
        self._fields.0 = value;
        self
    }
}

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

impl<'a, S: recipe_state::State> RecipeBuilder<'a, S> {
    /// Set the `image` field (optional)
    pub fn image(mut self, value: impl Into<Option<BlobRef<'a>>>) -> 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<'a>>) -> Self {
        self._fields.2 = value;
        self
    }
}

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

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

impl<'a, S: recipe_state::State> RecipeBuilder<'a, 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<'a, S> RecipeBuilder<'a, S>
where
    S: recipe_state::State,
    S::Title: recipe_state::IsUnset,
{
    /// Set the `title` field (required)
    pub fn title(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> RecipeBuilder<'a, recipe_state::SetTitle<S>> {
        self._fields.7 = Option::Some(value.into());
        RecipeBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> RecipeBuilder<'a, S>
where
    S: recipe_state::State,
    S::Title: recipe_state::IsSet,
    S::Steps: recipe_state::IsSet,
    S::Ingredients: recipe_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Recipe<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Recipe<'a> {
        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),
        }
    }
}