// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: pub.quizzy.answer
//
// 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, Datetime};
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::com_atproto::repo::strong_ref::StrongRef;
/// A person's answer to a question

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Answer<'a> {
    ///How certain the person is about this answer
    #[serde(borrow)]
    pub certainty: AnswerCertainty<'a>,
    ///Reference to the question being answered
    #[serde(borrow)]
    pub question: StrongRef<'a>,
    ///The answer text
    #[serde(borrow)]
    pub text: CowStr<'a>,
    ///When this answer was submitted
    pub timestamp: Datetime,
}

/// How certain the person is about this answer

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum AnswerCertainty<'a> {
    DeadCertain,
    FairlySure,
    EducatedGuess,
    WildGuess,
    Other(CowStr<'a>),
}

impl<'a> AnswerCertainty<'a> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::DeadCertain => "deadCertain",
            Self::FairlySure => "fairlySure",
            Self::EducatedGuess => "educatedGuess",
            Self::WildGuess => "wildGuess",
            Self::Other(s) => s.as_ref(),
        }
    }
}

impl<'a> From<&'a str> for AnswerCertainty<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "deadCertain" => Self::DeadCertain,
            "fairlySure" => Self::FairlySure,
            "educatedGuess" => Self::EducatedGuess,
            "wildGuess" => Self::WildGuess,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for AnswerCertainty<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "deadCertain" => Self::DeadCertain,
            "fairlySure" => Self::FairlySure,
            "educatedGuess" => Self::EducatedGuess,
            "wildGuess" => Self::WildGuess,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

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

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

impl<'a> serde::Serialize for AnswerCertainty<'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 AnswerCertainty<'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 AnswerCertainty<'a> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl jacquard_common::IntoStatic for AnswerCertainty<'_> {
    type Output = AnswerCertainty<'static>;
    fn into_static(self) -> Self::Output {
        match self {
            AnswerCertainty::DeadCertain => AnswerCertainty::DeadCertain,
            AnswerCertainty::FairlySure => AnswerCertainty::FairlySure,
            AnswerCertainty::EducatedGuess => AnswerCertainty::EducatedGuess,
            AnswerCertainty::WildGuess => AnswerCertainty::WildGuess,
            AnswerCertainty::Other(v) => AnswerCertainty::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 AnswerGetRecordOutput<'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: Answer<'a>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct AnswerRecord;
impl XrpcResp for AnswerRecord {
    const NSID: &'static str = "pub.quizzy.answer";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = AnswerGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Answer<'_> {
    const NSID: &'static str = "pub.quizzy.answer";
    type Record = AnswerRecord;
}

impl Collection for AnswerRecord {
    const NSID: &'static str = "pub.quizzy.answer";
    type Record = AnswerRecord;
}

impl<'a> LexiconSchema for Answer<'a> {
    fn nsid() -> &'static str {
        "pub.quizzy.answer"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_pub_quizzy_answer()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.text;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 1000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("text"),
                    max: 1000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.text;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 100usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("text"),
                        max: 100usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

pub mod answer_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 Question;
        type Certainty;
        type Text;
        type Timestamp;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Question = Unset;
        type Certainty = Unset;
        type Text = Unset;
        type Timestamp = Unset;
    }
    ///State transition - sets the `question` field to Set
    pub struct SetQuestion<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetQuestion<S> {}
    impl<S: State> State for SetQuestion<S> {
        type Question = Set<members::question>;
        type Certainty = S::Certainty;
        type Text = S::Text;
        type Timestamp = S::Timestamp;
    }
    ///State transition - sets the `certainty` field to Set
    pub struct SetCertainty<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetCertainty<S> {}
    impl<S: State> State for SetCertainty<S> {
        type Question = S::Question;
        type Certainty = Set<members::certainty>;
        type Text = S::Text;
        type Timestamp = S::Timestamp;
    }
    ///State transition - sets the `text` field to Set
    pub struct SetText<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetText<S> {}
    impl<S: State> State for SetText<S> {
        type Question = S::Question;
        type Certainty = S::Certainty;
        type Text = Set<members::text>;
        type Timestamp = S::Timestamp;
    }
    ///State transition - sets the `timestamp` field to Set
    pub struct SetTimestamp<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetTimestamp<S> {}
    impl<S: State> State for SetTimestamp<S> {
        type Question = S::Question;
        type Certainty = S::Certainty;
        type Text = S::Text;
        type Timestamp = Set<members::timestamp>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `question` field
        pub struct question(());
        ///Marker type for the `certainty` field
        pub struct certainty(());
        ///Marker type for the `text` field
        pub struct text(());
        ///Marker type for the `timestamp` field
        pub struct timestamp(());
    }
}

/// Builder for constructing an instance of this type
pub struct AnswerBuilder<'a, S: answer_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<AnswerCertainty<'a>>,
        Option<StrongRef<'a>>,
        Option<CowStr<'a>>,
        Option<Datetime>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Answer<'a> {
    /// Create a new builder for this type
    pub fn new() -> AnswerBuilder<'a, answer_state::Empty> {
        AnswerBuilder::new()
    }
}

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

impl<'a, S> AnswerBuilder<'a, S>
where
    S: answer_state::State,
    S::Certainty: answer_state::IsUnset,
{
    /// Set the `certainty` field (required)
    pub fn certainty(
        mut self,
        value: impl Into<AnswerCertainty<'a>>,
    ) -> AnswerBuilder<'a, answer_state::SetCertainty<S>> {
        self._fields.0 = Option::Some(value.into());
        AnswerBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> AnswerBuilder<'a, S>
where
    S: answer_state::State,
    S::Question: answer_state::IsUnset,
{
    /// Set the `question` field (required)
    pub fn question(
        mut self,
        value: impl Into<StrongRef<'a>>,
    ) -> AnswerBuilder<'a, answer_state::SetQuestion<S>> {
        self._fields.1 = Option::Some(value.into());
        AnswerBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> AnswerBuilder<'a, S>
where
    S: answer_state::State,
    S::Text: answer_state::IsUnset,
{
    /// Set the `text` field (required)
    pub fn text(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> AnswerBuilder<'a, answer_state::SetText<S>> {
        self._fields.2 = Option::Some(value.into());
        AnswerBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> AnswerBuilder<'a, S>
where
    S: answer_state::State,
    S::Timestamp: answer_state::IsUnset,
{
    /// Set the `timestamp` field (required)
    pub fn timestamp(
        mut self,
        value: impl Into<Datetime>,
    ) -> AnswerBuilder<'a, answer_state::SetTimestamp<S>> {
        self._fields.3 = Option::Some(value.into());
        AnswerBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> AnswerBuilder<'a, S>
where
    S: answer_state::State,
    S::Question: answer_state::IsSet,
    S::Certainty: answer_state::IsSet,
    S::Text: answer_state::IsSet,
    S::Timestamp: answer_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Answer<'a> {
        Answer {
            certainty: self._fields.0.unwrap(),
            question: self._fields.1.unwrap(),
            text: self._fields.2.unwrap(),
            timestamp: self._fields.3.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>,
        >,
    ) -> Answer<'a> {
        Answer {
            certainty: self._fields.0.unwrap(),
            question: self._fields.1.unwrap(),
            text: self._fields.2.unwrap(),
            timestamp: self._fields.3.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_pub_quizzy_answer() -> 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("pub.quizzy.answer"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static("A person's answer to a question"),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("question"),
                                SmolStr::new_static("text"),
                                SmolStr::new_static("certainty"),
                                SmolStr::new_static("timestamp")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("certainty"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "How certain the person is about this answer",
                                        ),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("question"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("com.atproto.repo.strongRef"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("text"),
                                LexObjectProperty::String(LexString {
                                    description: Some(CowStr::new_static("The answer text")),
                                    max_length: Some(1000usize),
                                    max_graphemes: Some(100usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("timestamp"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("When this answer was submitted"),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}