// @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, 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::quiz_score;
/// Final rankings for a completed quiz

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "pub.quizzy.quizScore",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct QuizScore<S: BosStr = DefaultStr> {
    ///Reference to the quizBegin record
    pub quiz_begin: StrongRef<S>,
    ///Ordered list of team results (by ranking)
    pub results: Vec<quiz_score::TeamResult<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 QuizScoreGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: QuizScore<S>,
}

/// A team's final result

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct TeamResult<S: BosStr = DefaultStr> {
    ///Reference to the team's detailed score record
    pub team_score: StrongRef<S>,
    ///Team's total score
    pub total_score: i64,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

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

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

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

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

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

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

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

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

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

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

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

impl<St, S: BosStr> QuizScoreBuilder<St, S>
where
    St: quiz_score_state::State,
    St::QuizBegin: quiz_score_state::IsSet,
    St::Results: quiz_score_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> QuizScore<S> {
        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<SmolStr, Data<S>>,
    ) -> QuizScore<S> {
        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<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetTeamScore<St> {}
    impl<St: State> State for SetTeamScore<St> {
        type TeamScore = Set<members::team_score>;
        type TotalScore = St::TotalScore;
    }
    ///State transition - sets the `total_score` field to Set
    pub struct SetTotalScore<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetTotalScore<St> {}
    impl<St: State> State for SetTotalScore<St> {
        type TeamScore = St::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<St: team_result_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (Option<StrongRef<S>>, Option<i64>),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

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

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

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