// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: social.lexical.works.work
//
// 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};
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};

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "social.lexical.works.work",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Work<S: BosStr = DefaultStr> {
    ///
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<S>,
    ///
    pub title: S,
    ///
    pub work_type: WorkWorkType<S>,
    ///
    #[serde(skip_serializing_if = "Option::is_none")]
    pub year: Option<i64>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


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

impl<S: BosStr> WorkWorkType<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Movie => "Movie",
            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() {
            "Movie" => Self::Movie,
            _ => Self::Other(s),
        }
    }
}

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

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

impl<S: BosStr> Serialize for WorkWorkType<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 WorkWorkType<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 WorkWorkType<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for WorkWorkType<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = WorkWorkType<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            WorkWorkType::Movie => WorkWorkType::Movie,
            WorkWorkType::Other(v) => WorkWorkType::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 WorkGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Work<S>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct WorkRecord;
impl XrpcResp for WorkRecord {
    const NSID: &'static str = "social.lexical.works.work";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = WorkGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Work<S> {
    const NSID: &'static str = "social.lexical.works.work";
    type Record = WorkRecord;
}

impl Collection for WorkRecord {
    const NSID: &'static str = "social.lexical.works.work";
    type Record = WorkRecord;
}

impl<S: BosStr> LexiconSchema for Work<S> {
    fn nsid() -> &'static str {
        "social.lexical.works.work"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_social_lexical_works_work()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.id {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 64usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("id"),
                    max: 64usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.id {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 32usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("id"),
                        max: 32usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let value = &self.title;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 1024usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("title"),
                    max: 1024usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.title;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 512usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("title"),
                        max: 512usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let value = &self.work_type;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 128usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("work_type"),
                    max: 128usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.work_type;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 64usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("work_type"),
                        max: 64usize,
                        actual: count,
                    });
                }
            }
        }
        if let Some(ref value) = self.year {
            if *value > 2199i64 {
                return Err(ConstraintError::Maximum {
                    path: ValidationPath::from_field("year"),
                    max: 2199i64,
                    actual: *value,
                });
            }
        }
        if let Some(ref value) = self.year {
            if *value < 0i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("year"),
                    min: 0i64,
                    actual: *value,
                });
            }
        }
        Ok(())
    }
}

pub mod work_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 WorkType;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Title = Unset;
        type WorkType = Unset;
    }
    ///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 Title = Set<members::title>;
        type WorkType = St::WorkType;
    }
    ///State transition - sets the `work_type` field to Set
    pub struct SetWorkType<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetWorkType<St> {}
    impl<St: State> State for SetWorkType<St> {
        type Title = St::Title;
        type WorkType = Set<members::work_type>;
    }
    /// 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 `work_type` field
        pub struct work_type(());
    }
}

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

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

impl<S: BosStr> Work<S> {
    /// Create a new builder for this type
    pub fn builder() -> WorkBuilder<work_state::Empty, S> {
        WorkBuilder::builder()
    }
}

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

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

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

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

impl<St, S: BosStr> WorkBuilder<St, S>
where
    St: work_state::State,
    St::WorkType: work_state::IsUnset,
{
    /// Set the `workType` field (required)
    pub fn work_type(
        mut self,
        value: impl Into<WorkWorkType<S>>,
    ) -> WorkBuilder<work_state::SetWorkType<St>, S> {
        self._fields.2 = Option::Some(value.into());
        WorkBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

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

impl<St, S: BosStr> WorkBuilder<St, S>
where
    St: work_state::State,
    St::Title: work_state::IsSet,
    St::WorkType: work_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Work<S> {
        Work {
            id: self._fields.0,
            title: self._fields.1.unwrap(),
            work_type: self._fields.2.unwrap(),
            year: self._fields.3,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(self, extra_data: BTreeMap<SmolStr, Data<S>>) -> Work<S> {
        Work {
            id: self._fields.0,
            title: self._fields.1.unwrap(),
            work_type: self._fields.2.unwrap(),
            year: self._fields.3,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_social_lexical_works_work() -> 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("social.lexical.works.work"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(CowStr::new_static("")),
                    key: Some(CowStr::new_static("any")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("title"),
                                SmolStr::new_static("workType")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("id"),
                                LexObjectProperty::String(LexString {
                                    description: Some(CowStr::new_static("")),
                                    max_length: Some(64usize),
                                    max_graphemes: Some(32usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("title"),
                                LexObjectProperty::String(LexString {
                                    description: Some(CowStr::new_static("")),
                                    max_length: Some(1024usize),
                                    max_graphemes: Some(512usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("workType"),
                                LexObjectProperty::String(LexString {
                                    description: Some(CowStr::new_static("")),
                                    max_length: Some(128usize),
                                    max_graphemes: Some(64usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("year"),
                                LexObjectProperty::Integer(LexInteger {
                                    minimum: Some(0i64),
                                    maximum: Some(2199i64),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}