// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: pub.quizzy.quizScore
//
// 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::quiz_score;
/// Final rankings for a completed quiz

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct QuizScore<'a> {
    ///Reference to the quizBegin record
    #[serde(borrow)]
    pub quiz_begin: StrongRef<'a>,
    ///Ordered list of team results (by ranking)
    #[serde(borrow)]
    pub results: Vec<quiz_score::TeamResult<'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 QuizScoreGetRecordOutput<'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: QuizScore<'a>,
}

/// A team's final result

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct TeamResult<'a> {
    ///Reference to the team's detailed score record
    #[serde(borrow)]
    pub team_score: StrongRef<'a>,
    ///Team's total score
    pub total_score: i64,
}

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

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

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

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

impl Collection for QuizScore<'_> {
    const NSID: &'static str = "pub.quizzy.quizScore";
    type Record = QuizScoreRecord;
}

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

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

impl<'a> LexiconSchema for TeamResult<'a> {
    fn nsid() -> &'static str {
        "pub.quizzy.quizScore"
    }
    fn def_name() -> &'static str {
        "teamResult"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_pub_quizzy_quizScore()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.total_score;
            if *value < 0i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("total_score"),
                    min: 0i64,
                    actual: *value,
                });
            }
        }
        Ok(())
    }
}

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

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

impl<'a> QuizScore<'a> {
    /// Create a new builder for this type
    pub fn new() -> QuizScoreBuilder<'a, quiz_score_state::Empty> {
        QuizScoreBuilder::new()
    }
}

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

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

impl<'a, S> QuizScoreBuilder<'a, S>
where
    S: quiz_score_state::State,
    S::Results: quiz_score_state::IsUnset,
{
    /// Set the `results` field (required)
    pub fn results(
        mut self,
        value: impl Into<Vec<quiz_score::TeamResult<'a>>>,
    ) -> QuizScoreBuilder<'a, quiz_score_state::SetResults<S>> {
        self._fields.1 = Option::Some(value.into());
        QuizScoreBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> QuizScoreBuilder<'a, S>
where
    S: quiz_score_state::State,
    S::Results: quiz_score_state::IsSet,
    S::QuizBegin: quiz_score_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> QuizScore<'a> {
        QuizScore {
            quiz_begin: self._fields.0.unwrap(),
            results: self._fields.1.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>,
        >,
    ) -> QuizScore<'a> {
        QuizScore {
            quiz_begin: self._fields.0.unwrap(),
            results: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_pub_quizzy_quizScore() -> 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.quizScore"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static("Final rankings for a completed quiz"),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("quizBegin"),
                                SmolStr::new_static("results")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            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("results"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Ordered list of team results (by ranking)",
                                        ),
                                    ),
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#teamResult"),
                                        ..Default::default()
                                    }),
                                    min_length: Some(1usize),
                                    max_length: Some(100usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("teamResult"),
                LexUserType::Object(LexObject {
                    description: Some(CowStr::new_static("A team's final result")),
                    required: Some(
                        vec![
                            SmolStr::new_static("teamScore"),
                            SmolStr::new_static("totalScore")
                        ],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("teamScore"),
                            LexObjectProperty::Ref(LexRef {
                                r#ref: CowStr::new_static("com.atproto.repo.strongRef"),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("totalScore"),
                            LexObjectProperty::Integer(LexInteger {
                                minimum: Some(0i64),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod team_result_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 TeamScore;
        type TotalScore;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type TeamScore = Unset;
        type TotalScore = Unset;
    }
    ///State transition - sets the `team_score` field to Set
    pub struct SetTeamScore<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetTeamScore<S> {}
    impl<S: State> State for SetTeamScore<S> {
        type TeamScore = Set<members::team_score>;
        type TotalScore = S::TotalScore;
    }
    ///State transition - sets the `total_score` field to Set
    pub struct SetTotalScore<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetTotalScore<S> {}
    impl<S: State> State for SetTotalScore<S> {
        type TeamScore = S::TeamScore;
        type TotalScore = Set<members::total_score>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `team_score` field
        pub struct team_score(());
        ///Marker type for the `total_score` field
        pub struct total_score(());
    }
}

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

impl<'a> TeamResult<'a> {
    /// Create a new builder for this type
    pub fn new() -> TeamResultBuilder<'a, team_result_state::Empty> {
        TeamResultBuilder::new()
    }
}

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

impl<'a, S> TeamResultBuilder<'a, S>
where
    S: team_result_state::State,
    S::TeamScore: team_result_state::IsUnset,
{
    /// Set the `teamScore` field (required)
    pub fn team_score(
        mut self,
        value: impl Into<StrongRef<'a>>,
    ) -> TeamResultBuilder<'a, team_result_state::SetTeamScore<S>> {
        self._fields.0 = Option::Some(value.into());
        TeamResultBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> TeamResultBuilder<'a, S>
where
    S: team_result_state::State,
    S::TotalScore: team_result_state::IsUnset,
{
    /// Set the `totalScore` field (required)
    pub fn total_score(
        mut self,
        value: impl Into<i64>,
    ) -> TeamResultBuilder<'a, team_result_state::SetTotalScore<S>> {
        self._fields.1 = Option::Some(value.into());
        TeamResultBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> TeamResultBuilder<'a, S>
where
    S: team_result_state::State,
    S::TeamScore: team_result_state::IsSet,
    S::TotalScore: team_result_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> TeamResult<'a> {
        TeamResult {
            team_score: self._fields.0.unwrap(),
            total_score: self._fields.1.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>,
        >,
    ) -> TeamResult<'a> {
        TeamResult {
            team_score: self._fields.0.unwrap(),
            total_score: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}