// @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, 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};
use crate::com_atproto::repo::strong_ref::StrongRef;
use crate::pub_quizzy::team_score;
/// A team's scored answers for a quiz

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "pub.quizzy.teamScore",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct TeamScore<S: BosStr = DefaultStr> {
    ///Scored answers for this team
    pub answers: Vec<team_score::ScoredAnswer<S>>,
    ///Reference to the quizBegin record
    pub quiz_begin: StrongRef<S>,
    ///Reference to the team
    pub team: StrongRef<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

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

/// An answer with scores for each expected answer

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct ScoredAnswer<S: BosStr = DefaultStr> {
    ///Reference to the answer record
    pub answer: StrongRef<S>,
    ///Optional commentary from the quiz master
    #[serde(skip_serializing_if = "Option::is_none")]
    pub commentary: Option<S>,
    ///Points awarded for each expected answer in the question
    pub scores: Vec<i64>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

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

/// 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<S: BosStr> = TeamScoreGetRecordOutput<S>;
    type Err = RecordError;
}

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

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

/// Builder for constructing an instance of this type.
pub struct TeamScoreBuilder<St: team_score_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Vec<team_score::ScoredAnswer<S>>>,
        Option<StrongRef<S>>,
        Option<StrongRef<S>>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

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

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

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

impl<St, S: BosStr> TeamScoreBuilder<St, S>
where
    St: team_score_state::State,
    St::Answers: team_score_state::IsSet,
    St::QuizBegin: team_score_state::IsSet,
    St::Team: team_score_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> TeamScore<S> {
        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<SmolStr, Data<S>>,
    ) -> TeamScore<S> {
        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 Answer;
        type Scores;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Answer = Unset;
        type Scores = Unset;
    }
    ///State transition - sets the `answer` field to Set
    pub struct SetAnswer<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetAnswer<St> {}
    impl<St: State> State for SetAnswer<St> {
        type Answer = Set<members::answer>;
        type Scores = St::Scores;
    }
    ///State transition - sets the `scores` field to Set
    pub struct SetScores<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetScores<St> {}
    impl<St: State> State for SetScores<St> {
        type Answer = St::Answer;
        type Scores = Set<members::scores>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `answer` field
        pub struct answer(());
        ///Marker type for the `scores` field
        pub struct scores(());
    }
}

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

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

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

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

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

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

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

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

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