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

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "app.mathr.leaderboard.entry",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Entry<S: BosStr = DefaultStr> {
    ///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")]
    pub player_avatar: Option<UriValue<S>>,
    ///The DID of the player who achieved this score
    pub player_did: Did<S>,
    ///The player's display name at the time of submission
    #[serde(skip_serializing_if = "Option::is_none")]
    pub player_display_name: Option<S>,
    ///The player's handle at the time of submission
    #[serde(skip_serializing_if = "Option::is_none")]
    pub player_handle: Option<S>,
    ///Optional AT URI to the player's Bluesky post announcing the score
    #[serde(skip_serializing_if = "Option::is_none")]
    pub post_uri: Option<AtUri<S>>,
    ///Total number of challenges attempted
    pub total_challenges: i64,
    ///Total number of correct answers
    pub total_successes: i64,
    #[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 EntryGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Entry<S>,
}

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

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

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

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

/// Builder for constructing an instance of this type.
pub struct EntryBuilder<St: entry_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Datetime>,
        Option<i64>,
        Option<i64>,
        Option<UriValue<S>>,
        Option<Did<S>>,
        Option<S>,
        Option<S>,
        Option<AtUri<S>>,
        Option<i64>,
        Option<i64>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

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

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

impl<St: entry_state::State, S: BosStr> EntryBuilder<St, 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<St: entry_state::State, S: BosStr> EntryBuilder<St, S> {
    /// Set the `playerAvatar` field (optional)
    pub fn player_avatar(mut self, value: impl Into<Option<UriValue<S>>>) -> 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<S>>) -> Self {
        self._fields.3 = value;
        self
    }
}

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

impl<St: entry_state::State, S: BosStr> EntryBuilder<St, S> {
    /// Set the `playerDisplayName` field (optional)
    pub fn player_display_name(mut self, value: impl Into<Option<S>>) -> 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<S>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<St: entry_state::State, S: BosStr> EntryBuilder<St, S> {
    /// Set the `playerHandle` field (optional)
    pub fn player_handle(mut self, value: impl Into<Option<S>>) -> 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<S>) -> Self {
        self._fields.6 = value;
        self
    }
}

impl<St: entry_state::State, S: BosStr> EntryBuilder<St, S> {
    /// Set the `postUri` field (optional)
    pub fn post_uri(mut self, value: impl Into<Option<AtUri<S>>>) -> 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<S>>) -> Self {
        self._fields.7 = value;
        self
    }
}

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

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

impl<St, S: BosStr> EntryBuilder<St, S>
where
    St: entry_state::State,
    St::CreatedAt: entry_state::IsSet,
    St::Level: entry_state::IsSet,
    St::PlayerDid: entry_state::IsSet,
    St::TotalChallenges: entry_state::IsSet,
    St::TotalSuccesses: entry_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Entry<S> {
        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<SmolStr, Data<S>>) -> Entry<S> {
        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()
    }
}