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

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

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Work<'a> {
    ///
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub id: Option<CowStr<'a>>,
    ///
    #[serde(borrow)]
    pub title: CowStr<'a>,
    ///
    #[serde(borrow)]
    pub work_type: WorkWorkType<'a>,
    ///
    #[serde(skip_serializing_if = "Option::is_none")]
    pub year: Option<i64>,
}

///

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum WorkWorkType<'a> {
    Movie,
    Other(CowStr<'a>),
}

impl<'a> WorkWorkType<'a> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Movie => "Movie",
            Self::Other(s) => s.as_ref(),
        }
    }
}

impl<'a> From<&'a str> for WorkWorkType<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "Movie" => Self::Movie,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for WorkWorkType<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "Movie" => Self::Movie,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

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

impl<'a> AsRef<str> for WorkWorkType<'a> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

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

impl<'de, 'a> serde::Deserialize<'de> for WorkWorkType<'a>
where
    'de: 'a,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = <&'de str>::deserialize(deserializer)?;
        Ok(Self::from(s))
    }
}

impl<'a> Default for WorkWorkType<'a> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl jacquard_common::IntoStatic for WorkWorkType<'_> {
    type Output = WorkWorkType<'static>;
    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<'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: Work<'a>,
}

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

/// 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<'de> = WorkGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Work<'_> {
    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<'a> LexiconSchema for Work<'a> {
    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<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 WorkType = S::WorkType;
    }
    ///State transition - sets the `work_type` field to Set
    pub struct SetWorkType<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetWorkType<S> {}
    impl<S: State> State for SetWorkType<S> {
        type Title = S::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<'a, S: work_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
        Option<WorkWorkType<'a>>,
        Option<i64>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

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

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

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

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

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

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