// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: org.stormlightlabs.malfestio.deck
//
// 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};
/// A collection of flashcards and sources.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "org.stormlightlabs.malfestio.deck",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Deck<S: BosStr = DefaultStr> {
    ///Ordered list of references to cards in this deck.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub card_refs: Option<Vec<AtUri<S>>>,
    pub created_at: Datetime,
    ///Description of the deck context.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<S>,
    ///Language code for the deck content (e.g., 'en', 'es', 'fr').
    #[serde(skip_serializing_if = "Option::is_none")]
    pub language: Option<S>,
    ///License for the deck content.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub license: Option<S>,
    ///References to source materials (articles, lectures) used in this deck.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_refs: Option<Vec<AtUri<S>>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<S>>,
    ///Title of the deck.
    pub title: S,
    ///Timestamp of last update.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<Datetime>,
    ///Visibility setting for the deck.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visibility: Option<DeckVisibility<S>>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// Visibility setting for the deck.

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum DeckVisibility<S: BosStr = DefaultStr> {
    Private,
    Unlisted,
    Public,
    Other(S),
}

impl<S: BosStr> DeckVisibility<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Private => "private",
            Self::Unlisted => "unlisted",
            Self::Public => "public",
            Self::Other(s) => s.as_ref(),
        }
    }
    /// Construct from a string-like value, matching known values.
    pub fn from_value(s: S) -> Self {
        match s.as_ref() {
            "private" => Self::Private,
            "unlisted" => Self::Unlisted,
            "public" => Self::Public,
            _ => Self::Other(s),
        }
    }
}

impl<S: BosStr> core::fmt::Display for DeckVisibility<S> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl<S: BosStr> AsRef<str> for DeckVisibility<S> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<S: BosStr> Serialize for DeckVisibility<S> {
    fn serialize<Ser>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
    where
        Ser: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de, S: Deserialize<'de> + BosStr> Deserialize<'de> for DeckVisibility<S> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = S::deserialize(deserializer)?;
        Ok(Self::from_value(s))
    }
}

impl<S: BosStr + Default> Default for DeckVisibility<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for DeckVisibility<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = DeckVisibility<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            DeckVisibility::Private => DeckVisibility::Private,
            DeckVisibility::Unlisted => DeckVisibility::Unlisted,
            DeckVisibility::Public => DeckVisibility::Public,
            DeckVisibility::Other(v) => DeckVisibility::Other(v.into_static()),
        }
    }
}

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

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct DeckRecord;
impl XrpcResp for DeckRecord {
    const NSID: &'static str = "org.stormlightlabs.malfestio.deck";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = DeckGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Deck<S> {
    const NSID: &'static str = "org.stormlightlabs.malfestio.deck";
    type Record = DeckRecord;
}

impl Collection for DeckRecord {
    const NSID: &'static str = "org.stormlightlabs.malfestio.deck";
    type Record = DeckRecord;
}

impl<S: BosStr> LexiconSchema for Deck<S> {
    fn nsid() -> &'static str {
        "org.stormlightlabs.malfestio.deck"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_org_stormlightlabs_malfestio_deck()
    }
    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.language {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 20usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("language"),
                    max: 20usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.license {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 500usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("license"),
                    max: 500usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.tags {
            #[allow(unused_comparisons)]
            if value.len() > 64usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("tags"),
                    max: 64usize,
                    actual: value.len(),
                });
            }
        }
        {
            let value = &self.title;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 300usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("title"),
                    max: 300usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.visibility {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 100usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("visibility"),
                    max: 100usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

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

/// Builder for constructing an instance of this type.
pub struct DeckBuilder<St: deck_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Vec<AtUri<S>>>,
        Option<Datetime>,
        Option<S>,
        Option<S>,
        Option<S>,
        Option<Vec<AtUri<S>>>,
        Option<Vec<S>>,
        Option<S>,
        Option<Datetime>,
        Option<DeckVisibility<S>>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> Deck<S> {
    /// Create a new builder for this type
    pub fn builder() -> DeckBuilder<deck_state::Empty, S> {
        DeckBuilder::builder()
    }
}

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

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

impl<St: deck_state::State, S: BosStr> DeckBuilder<St, S> {
    /// Set the `cardRefs` field (optional)
    pub fn card_refs(mut self, value: impl Into<Option<Vec<AtUri<S>>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `cardRefs` field to an Option value (optional)
    pub fn maybe_card_refs(mut self, value: Option<Vec<AtUri<S>>>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St, S: BosStr> DeckBuilder<St, S>
where
    St: deck_state::State,
    St::CreatedAt: deck_state::IsUnset,
{
    /// Set the `createdAt` field (required)
    pub fn created_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> DeckBuilder<deck_state::SetCreatedAt<St>, S> {
        self._fields.1 = Option::Some(value.into());
        DeckBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

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

impl<St: deck_state::State, S: BosStr> DeckBuilder<St, S> {
    /// Set the `language` field (optional)
    pub fn language(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `language` field to an Option value (optional)
    pub fn maybe_language(mut self, value: Option<S>) -> Self {
        self._fields.3 = value;
        self
    }
}

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

impl<St: deck_state::State, S: BosStr> DeckBuilder<St, S> {
    /// Set the `sourceRefs` field (optional)
    pub fn source_refs(mut self, value: impl Into<Option<Vec<AtUri<S>>>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `sourceRefs` field to an Option value (optional)
    pub fn maybe_source_refs(mut self, value: Option<Vec<AtUri<S>>>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<St: deck_state::State, S: BosStr> DeckBuilder<St, S> {
    /// Set the `tags` field (optional)
    pub fn tags(mut self, value: impl Into<Option<Vec<S>>>) -> Self {
        self._fields.6 = value.into();
        self
    }
    /// Set the `tags` field to an Option value (optional)
    pub fn maybe_tags(mut self, value: Option<Vec<S>>) -> Self {
        self._fields.6 = value;
        self
    }
}

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

impl<St: deck_state::State, S: BosStr> DeckBuilder<St, S> {
    /// Set the `updatedAt` field (optional)
    pub fn updated_at(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.8 = value.into();
        self
    }
    /// Set the `updatedAt` field to an Option value (optional)
    pub fn maybe_updated_at(mut self, value: Option<Datetime>) -> Self {
        self._fields.8 = value;
        self
    }
}

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

impl<St, S: BosStr> DeckBuilder<St, S>
where
    St: deck_state::State,
    St::CreatedAt: deck_state::IsSet,
    St::Title: deck_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Deck<S> {
        Deck {
            card_refs: self._fields.0,
            created_at: self._fields.1.unwrap(),
            description: self._fields.2,
            language: self._fields.3,
            license: self._fields.4,
            source_refs: self._fields.5,
            tags: self._fields.6,
            title: self._fields.7.unwrap(),
            updated_at: self._fields.8,
            visibility: self._fields.9,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(self, extra_data: BTreeMap<SmolStr, Data<S>>) -> Deck<S> {
        Deck {
            card_refs: self._fields.0,
            created_at: self._fields.1.unwrap(),
            description: self._fields.2,
            language: self._fields.3,
            license: self._fields.4,
            source_refs: self._fields.5,
            tags: self._fields.6,
            title: self._fields.7.unwrap(),
            updated_at: self._fields.8,
            visibility: self._fields.9,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_org_stormlightlabs_malfestio_deck() -> 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.stormlightlabs.malfestio.deck"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static("A collection of flashcards and sources."),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("title"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("cardRefs"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Ordered list of references to cards in this deck.",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        format: Some(LexStringFormat::AtUri),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("description"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Description of the deck context."),
                                    ),
                                    max_length: Some(3000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("language"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Language code for the deck content (e.g., 'en', 'es', 'fr').",
                                        ),
                                    ),
                                    max_length: Some(20usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("license"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("License for the deck content."),
                                    ),
                                    max_length: Some(500usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("sourceRefs"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "References to source materials (articles, lectures) used in this deck.",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        format: Some(LexStringFormat::AtUri),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("tags"),
                                LexObjectProperty::Array(LexArray {
                                    items: LexArrayItem::String(LexString {
                                        max_length: Some(100usize),
                                        ..Default::default()
                                    }),
                                    max_length: Some(64usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("title"),
                                LexObjectProperty::String(LexString {
                                    description: Some(CowStr::new_static("Title of the deck.")),
                                    max_length: Some(300usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("updatedAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Timestamp of last update."),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("visibility"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Visibility setting for the deck."),
                                    ),
                                    max_length: Some(100usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}