// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: app.mathr.leaderboard.entry
//
// 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::{Did, AtUri, Cid, Datetime, UriValue};
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};
/// A verified leaderboard entry stored in the mathr.app official repository

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Entry<'a> {
    ///Timestamp when the score was verified and added to the leaderboard
    pub created_at: Datetime,
    ///The highest level reached by the player
    pub level: i64,
    ///Success rate as a percentage (0-100)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub percentage: Option<i64>,
    ///URL to the player's avatar at the time of submission
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub player_avatar: Option<UriValue<'a>>,
    ///The DID of the player who achieved this score
    #[serde(borrow)]
    pub player_did: Did<'a>,
    ///The player's display name at the time of submission
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub player_display_name: Option<CowStr<'a>>,
    ///The player's handle at the time of submission
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub player_handle: Option<CowStr<'a>>,
    ///Optional AT URI to the player's Bluesky post announcing the score
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub post_uri: Option<AtUri<'a>>,
    ///Total number of challenges attempted
    pub total_challenges: i64,
    ///Total number of correct answers
    pub total_successes: i64,
}

/// 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 EntryGetRecordOutput<'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: Entry<'a>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct EntryRecord;
impl XrpcResp for EntryRecord {
    const NSID: &'static str = "app.mathr.leaderboard.entry";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = EntryGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Entry<'_> {
    const NSID: &'static str = "app.mathr.leaderboard.entry";
    type Record = EntryRecord;
}

impl Collection for EntryRecord {
    const NSID: &'static str = "app.mathr.leaderboard.entry";
    type Record = EntryRecord;
}

impl<'a> LexiconSchema for Entry<'a> {
    fn nsid() -> &'static str {
        "app.mathr.leaderboard.entry"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_mathr_leaderboard_entry()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.level;
            if *value < 1i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("level"),
                    min: 1i64,
                    actual: *value,
                });
            }
        }
        if let Some(ref value) = self.percentage {
            if *value > 100i64 {
                return Err(ConstraintError::Maximum {
                    path: ValidationPath::from_field("percentage"),
                    max: 100i64,
                    actual: *value,
                });
            }
        }
        if let Some(ref value) = self.percentage {
            if *value < 0i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("percentage"),
                    min: 0i64,
                    actual: *value,
                });
            }
        }
        {
            let value = &self.total_challenges;
            if *value < 1i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("total_challenges"),
                    min: 1i64,
                    actual: *value,
                });
            }
        }
        {
            let value = &self.total_successes;
            if *value < 0i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("total_successes"),
                    min: 0i64,
                    actual: *value,
                });
            }
        }
        Ok(())
    }
}

pub mod entry_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 Level;
        type TotalSuccesses;
        type TotalChallenges;
        type CreatedAt;
        type PlayerDid;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Level = Unset;
        type TotalSuccesses = Unset;
        type TotalChallenges = Unset;
        type CreatedAt = Unset;
        type PlayerDid = Unset;
    }
    ///State transition - sets the `level` field to Set
    pub struct SetLevel<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetLevel<S> {}
    impl<S: State> State for SetLevel<S> {
        type Level = Set<members::level>;
        type TotalSuccesses = S::TotalSuccesses;
        type TotalChallenges = S::TotalChallenges;
        type CreatedAt = S::CreatedAt;
        type PlayerDid = S::PlayerDid;
    }
    ///State transition - sets the `total_successes` field to Set
    pub struct SetTotalSuccesses<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetTotalSuccesses<S> {}
    impl<S: State> State for SetTotalSuccesses<S> {
        type Level = S::Level;
        type TotalSuccesses = Set<members::total_successes>;
        type TotalChallenges = S::TotalChallenges;
        type CreatedAt = S::CreatedAt;
        type PlayerDid = S::PlayerDid;
    }
    ///State transition - sets the `total_challenges` field to Set
    pub struct SetTotalChallenges<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetTotalChallenges<S> {}
    impl<S: State> State for SetTotalChallenges<S> {
        type Level = S::Level;
        type TotalSuccesses = S::TotalSuccesses;
        type TotalChallenges = Set<members::total_challenges>;
        type CreatedAt = S::CreatedAt;
        type PlayerDid = S::PlayerDid;
    }
    ///State transition - sets the `created_at` field to Set
    pub struct SetCreatedAt<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetCreatedAt<S> {}
    impl<S: State> State for SetCreatedAt<S> {
        type Level = S::Level;
        type TotalSuccesses = S::TotalSuccesses;
        type TotalChallenges = S::TotalChallenges;
        type CreatedAt = Set<members::created_at>;
        type PlayerDid = S::PlayerDid;
    }
    ///State transition - sets the `player_did` field to Set
    pub struct SetPlayerDid<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetPlayerDid<S> {}
    impl<S: State> State for SetPlayerDid<S> {
        type Level = S::Level;
        type TotalSuccesses = S::TotalSuccesses;
        type TotalChallenges = S::TotalChallenges;
        type CreatedAt = S::CreatedAt;
        type PlayerDid = Set<members::player_did>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `level` field
        pub struct level(());
        ///Marker type for the `total_successes` field
        pub struct total_successes(());
        ///Marker type for the `total_challenges` field
        pub struct total_challenges(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `player_did` field
        pub struct player_did(());
    }
}

/// Builder for constructing an instance of this type
pub struct EntryBuilder<'a, S: entry_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Datetime>,
        Option<i64>,
        Option<i64>,
        Option<UriValue<'a>>,
        Option<Did<'a>>,
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
        Option<AtUri<'a>>,
        Option<i64>,
        Option<i64>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Entry<'a> {
    /// Create a new builder for this type
    pub fn new() -> EntryBuilder<'a, entry_state::Empty> {
        EntryBuilder::new()
    }
}

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

impl<'a, S> EntryBuilder<'a, S>
where
    S: entry_state::State,
    S::CreatedAt: entry_state::IsUnset,
{
    /// Set the `createdAt` field (required)
    pub fn created_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> EntryBuilder<'a, entry_state::SetCreatedAt<S>> {
        self._fields.0 = Option::Some(value.into());
        EntryBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> EntryBuilder<'a, S>
where
    S: entry_state::State,
    S::Level: entry_state::IsUnset,
{
    /// Set the `level` field (required)
    pub fn level(
        mut self,
        value: impl Into<i64>,
    ) -> EntryBuilder<'a, entry_state::SetLevel<S>> {
        self._fields.1 = Option::Some(value.into());
        EntryBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: entry_state::State> EntryBuilder<'a, S> {
    /// Set the `percentage` field (optional)
    pub fn percentage(mut self, value: impl Into<Option<i64>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `percentage` field to an Option value (optional)
    pub fn maybe_percentage(mut self, value: Option<i64>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<'a, S: entry_state::State> EntryBuilder<'a, S> {
    /// Set the `playerAvatar` field (optional)
    pub fn player_avatar(mut self, value: impl Into<Option<UriValue<'a>>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `playerAvatar` field to an Option value (optional)
    pub fn maybe_player_avatar(mut self, value: Option<UriValue<'a>>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<'a, S> EntryBuilder<'a, S>
where
    S: entry_state::State,
    S::PlayerDid: entry_state::IsUnset,
{
    /// Set the `playerDid` field (required)
    pub fn player_did(
        mut self,
        value: impl Into<Did<'a>>,
    ) -> EntryBuilder<'a, entry_state::SetPlayerDid<S>> {
        self._fields.4 = Option::Some(value.into());
        EntryBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: entry_state::State> EntryBuilder<'a, S> {
    /// Set the `playerDisplayName` field (optional)
    pub fn player_display_name(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `playerDisplayName` field to an Option value (optional)
    pub fn maybe_player_display_name(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<'a, S: entry_state::State> EntryBuilder<'a, S> {
    /// Set the `playerHandle` field (optional)
    pub fn player_handle(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.6 = value.into();
        self
    }
    /// Set the `playerHandle` field to an Option value (optional)
    pub fn maybe_player_handle(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.6 = value;
        self
    }
}

impl<'a, S: entry_state::State> EntryBuilder<'a, S> {
    /// Set the `postUri` field (optional)
    pub fn post_uri(mut self, value: impl Into<Option<AtUri<'a>>>) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `postUri` field to an Option value (optional)
    pub fn maybe_post_uri(mut self, value: Option<AtUri<'a>>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<'a, S> EntryBuilder<'a, S>
where
    S: entry_state::State,
    S::TotalChallenges: entry_state::IsUnset,
{
    /// Set the `totalChallenges` field (required)
    pub fn total_challenges(
        mut self,
        value: impl Into<i64>,
    ) -> EntryBuilder<'a, entry_state::SetTotalChallenges<S>> {
        self._fields.8 = Option::Some(value.into());
        EntryBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> EntryBuilder<'a, S>
where
    S: entry_state::State,
    S::TotalSuccesses: entry_state::IsUnset,
{
    /// Set the `totalSuccesses` field (required)
    pub fn total_successes(
        mut self,
        value: impl Into<i64>,
    ) -> EntryBuilder<'a, entry_state::SetTotalSuccesses<S>> {
        self._fields.9 = Option::Some(value.into());
        EntryBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> EntryBuilder<'a, S>
where
    S: entry_state::State,
    S::Level: entry_state::IsSet,
    S::TotalSuccesses: entry_state::IsSet,
    S::TotalChallenges: entry_state::IsSet,
    S::CreatedAt: entry_state::IsSet,
    S::PlayerDid: entry_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Entry<'a> {
        Entry {
            created_at: self._fields.0.unwrap(),
            level: self._fields.1.unwrap(),
            percentage: self._fields.2,
            player_avatar: self._fields.3,
            player_did: self._fields.4.unwrap(),
            player_display_name: self._fields.5,
            player_handle: self._fields.6,
            post_uri: self._fields.7,
            total_challenges: self._fields.8.unwrap(),
            total_successes: self._fields.9.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>,
        >,
    ) -> Entry<'a> {
        Entry {
            created_at: self._fields.0.unwrap(),
            level: self._fields.1.unwrap(),
            percentage: self._fields.2,
            player_avatar: self._fields.3,
            player_did: self._fields.4.unwrap(),
            player_display_name: self._fields.5,
            player_handle: self._fields.6,
            post_uri: self._fields.7,
            total_challenges: self._fields.8.unwrap(),
            total_successes: self._fields.9.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_app_mathr_leaderboard_entry() -> 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("app.mathr.leaderboard.entry"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A verified leaderboard entry stored in the mathr.app official repository",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("playerDid"),
                                SmolStr::new_static("level"),
                                SmolStr::new_static("totalSuccesses"),
                                SmolStr::new_static("totalChallenges"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Timestamp when the score was verified and added to the leaderboard",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("level"),
                                LexObjectProperty::Integer(LexInteger {
                                    minimum: Some(1i64),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("percentage"),
                                LexObjectProperty::Integer(LexInteger {
                                    minimum: Some(0i64),
                                    maximum: Some(100i64),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("playerAvatar"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "URL to the player's avatar at the time of submission",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Uri),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("playerDid"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The DID of the player who achieved this score",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Did),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("playerDisplayName"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The player's display name at the time of submission",
                                        ),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("playerHandle"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The player's handle at the time of submission",
                                        ),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("postUri"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Optional AT URI to the player's Bluesky post announcing the score",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::AtUri),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("totalChallenges"),
                                LexObjectProperty::Integer(LexInteger {
                                    minimum: Some(1i64),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("totalSuccesses"),
                                LexObjectProperty::Integer(LexInteger {
                                    minimum: Some(0i64),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}