// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: pub.quizzy.teamScore
//
// 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};
use crate::com_atproto::repo::strong_ref::StrongRef;
use crate::pub_quizzy::team_score;
/// A team's scored answers for a quiz

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct TeamScore<'a> {
    ///Scored answers for this team
    #[serde(borrow)]
    pub answers: Vec<team_score::ScoredAnswer<'a>>,
    ///Reference to the quizBegin record
    #[serde(borrow)]
    pub quiz_begin: StrongRef<'a>,
    ///Reference to the team
    #[serde(borrow)]
    pub team: StrongRef<'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 TeamScoreGetRecordOutput<'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: TeamScore<'a>,
}

/// An answer with scores for each expected answer

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct ScoredAnswer<'a> {
    ///Reference to the answer record
    #[serde(borrow)]
    pub answer: StrongRef<'a>,
    ///Optional commentary from the quiz master
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub commentary: Option<CowStr<'a>>,
    ///Points awarded for each expected answer in the question
    pub scores: Vec<i64>,
}

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

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

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

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

impl Collection for TeamScore<'_> {
    const NSID: &'static str = "pub.quizzy.teamScore";
    type Record = TeamScoreRecord;
}

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

impl<'a> LexiconSchema for TeamScore<'a> {
    fn nsid() -> &'static str {
        "pub.quizzy.teamScore"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_pub_quizzy_teamScore()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.answers;
            #[allow(unused_comparisons)]
            if value.len() > 500usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("answers"),
                    max: 500usize,
                    actual: value.len(),
                });
            }
        }
        Ok(())
    }
}

impl<'a> LexiconSchema for ScoredAnswer<'a> {
    fn nsid() -> &'static str {
        "pub.quizzy.teamScore"
    }
    fn def_name() -> &'static str {
        "scoredAnswer"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_pub_quizzy_teamScore()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.commentary {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 5000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("commentary"),
                    max: 5000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.commentary {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 500usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("commentary"),
                        max: 500usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let value = &self.scores;
            #[allow(unused_comparisons)]
            if value.len() > 10usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("scores"),
                    max: 10usize,
                    actual: value.len(),
                });
            }
        }
        {
            let value = &self.scores;
            #[allow(unused_comparisons)]
            if value.len() < 1usize {
                return Err(ConstraintError::MinLength {
                    path: ValidationPath::from_field("scores"),
                    min: 1usize,
                    actual: value.len(),
                });
            }
        }
        Ok(())
    }
}

pub mod team_score_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 Team;
        type QuizBegin;
        type Answers;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Team = Unset;
        type QuizBegin = Unset;
        type Answers = Unset;
    }
    ///State transition - sets the `team` field to Set
    pub struct SetTeam<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetTeam<S> {}
    impl<S: State> State for SetTeam<S> {
        type Team = Set<members::team>;
        type QuizBegin = S::QuizBegin;
        type Answers = S::Answers;
    }
    ///State transition - sets the `quiz_begin` field to Set
    pub struct SetQuizBegin<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetQuizBegin<S> {}
    impl<S: State> State for SetQuizBegin<S> {
        type Team = S::Team;
        type QuizBegin = Set<members::quiz_begin>;
        type Answers = S::Answers;
    }
    ///State transition - sets the `answers` field to Set
    pub struct SetAnswers<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetAnswers<S> {}
    impl<S: State> State for SetAnswers<S> {
        type Team = S::Team;
        type QuizBegin = S::QuizBegin;
        type Answers = Set<members::answers>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `team` field
        pub struct team(());
        ///Marker type for the `quiz_begin` field
        pub struct quiz_begin(());
        ///Marker type for the `answers` field
        pub struct answers(());
    }
}

/// Builder for constructing an instance of this type
pub struct TeamScoreBuilder<'a, S: team_score_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Vec<team_score::ScoredAnswer<'a>>>,
        Option<StrongRef<'a>>,
        Option<StrongRef<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> TeamScore<'a> {
    /// Create a new builder for this type
    pub fn new() -> TeamScoreBuilder<'a, team_score_state::Empty> {
        TeamScoreBuilder::new()
    }
}

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

impl<'a, S> TeamScoreBuilder<'a, S>
where
    S: team_score_state::State,
    S::Answers: team_score_state::IsUnset,
{
    /// Set the `answers` field (required)
    pub fn answers(
        mut self,
        value: impl Into<Vec<team_score::ScoredAnswer<'a>>>,
    ) -> TeamScoreBuilder<'a, team_score_state::SetAnswers<S>> {
        self._fields.0 = Option::Some(value.into());
        TeamScoreBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> TeamScoreBuilder<'a, S>
where
    S: team_score_state::State,
    S::QuizBegin: team_score_state::IsUnset,
{
    /// Set the `quizBegin` field (required)
    pub fn quiz_begin(
        mut self,
        value: impl Into<StrongRef<'a>>,
    ) -> TeamScoreBuilder<'a, team_score_state::SetQuizBegin<S>> {
        self._fields.1 = Option::Some(value.into());
        TeamScoreBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> TeamScoreBuilder<'a, S>
where
    S: team_score_state::State,
    S::Team: team_score_state::IsUnset,
{
    /// Set the `team` field (required)
    pub fn team(
        mut self,
        value: impl Into<StrongRef<'a>>,
    ) -> TeamScoreBuilder<'a, team_score_state::SetTeam<S>> {
        self._fields.2 = Option::Some(value.into());
        TeamScoreBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> TeamScoreBuilder<'a, S>
where
    S: team_score_state::State,
    S::Team: team_score_state::IsSet,
    S::QuizBegin: team_score_state::IsSet,
    S::Answers: team_score_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> TeamScore<'a> {
        TeamScore {
            answers: self._fields.0.unwrap(),
            quiz_begin: self._fields.1.unwrap(),
            team: self._fields.2.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>,
        >,
    ) -> TeamScore<'a> {
        TeamScore {
            answers: self._fields.0.unwrap(),
            quiz_begin: self._fields.1.unwrap(),
            team: self._fields.2.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_pub_quizzy_teamScore() -> 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.teamScore"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static("A team's scored answers for a quiz"),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("quizBegin"),
                                SmolStr::new_static("team"), SmolStr::new_static("answers")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("answers"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static("Scored answers for this team"),
                                    ),
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#scoredAnswer"),
                                        ..Default::default()
                                    }),
                                    max_length: Some(500usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("quizBegin"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("com.atproto.repo.strongRef"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("team"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("com.atproto.repo.strongRef"),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("scoredAnswer"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "An answer with scores for each expected answer",
                        ),
                    ),
                    required: Some(
                        vec![
                            SmolStr::new_static("answer"), SmolStr::new_static("scores")
                        ],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("answer"),
                            LexObjectProperty::Ref(LexRef {
                                r#ref: CowStr::new_static("com.atproto.repo.strongRef"),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("commentary"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "Optional commentary from the quiz master",
                                    ),
                                ),
                                max_length: Some(5000usize),
                                max_graphemes: Some(500usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("scores"),
                            LexObjectProperty::Array(LexArray {
                                description: Some(
                                    CowStr::new_static(
                                        "Points awarded for each expected answer in the question",
                                    ),
                                ),
                                items: LexArrayItem::Integer(LexInteger {
                                    ..Default::default()
                                }),
                                min_length: Some(1usize),
                                max_length: Some(10usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod scored_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 Scores;
        type Answer;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Scores = Unset;
        type Answer = Unset;
    }
    ///State transition - sets the `scores` field to Set
    pub struct SetScores<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetScores<S> {}
    impl<S: State> State for SetScores<S> {
        type Scores = Set<members::scores>;
        type Answer = S::Answer;
    }
    ///State transition - sets the `answer` field to Set
    pub struct SetAnswer<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetAnswer<S> {}
    impl<S: State> State for SetAnswer<S> {
        type Scores = S::Scores;
        type Answer = Set<members::answer>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `scores` field
        pub struct scores(());
        ///Marker type for the `answer` field
        pub struct answer(());
    }
}

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

impl<'a> ScoredAnswer<'a> {
    /// Create a new builder for this type
    pub fn new() -> ScoredAnswerBuilder<'a, scored_answer_state::Empty> {
        ScoredAnswerBuilder::new()
    }
}

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

impl<'a, S> ScoredAnswerBuilder<'a, S>
where
    S: scored_answer_state::State,
    S::Answer: scored_answer_state::IsUnset,
{
    /// Set the `answer` field (required)
    pub fn answer(
        mut self,
        value: impl Into<StrongRef<'a>>,
    ) -> ScoredAnswerBuilder<'a, scored_answer_state::SetAnswer<S>> {
        self._fields.0 = Option::Some(value.into());
        ScoredAnswerBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

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

impl<'a, S> ScoredAnswerBuilder<'a, S>
where
    S: scored_answer_state::State,
    S::Scores: scored_answer_state::IsUnset,
{
    /// Set the `scores` field (required)
    pub fn scores(
        mut self,
        value: impl Into<Vec<i64>>,
    ) -> ScoredAnswerBuilder<'a, scored_answer_state::SetScores<S>> {
        self._fields.2 = Option::Some(value.into());
        ScoredAnswerBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> ScoredAnswerBuilder<'a, S>
where
    S: scored_answer_state::State,
    S::Scores: scored_answer_state::IsSet,
    S::Answer: scored_answer_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> ScoredAnswer<'a> {
        ScoredAnswer {
            answer: self._fields.0.unwrap(),
            commentary: self._fields.1,
            scores: self._fields.2.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>,
        >,
    ) -> ScoredAnswer<'a> {
        ScoredAnswer {
            answer: self._fields.0.unwrap(),
            commentary: self._fields.1,
            scores: self._fields.2.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}