// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: actor.rpg.master
//
// 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};
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 master record validating one player's stats for one system. Multiple GMs can validate the same player.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Master<'a> {
    ///Name of the campaign this validation relates to
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub campaign: Option<CowStr<'a>>,
    pub created_at: Datetime,
    ///DID of the player this record validates
    #[serde(borrow)]
    pub player: Did<'a>,
    ///What portions of stats are validated. 'none' = inherent trust (always valid), 'custom' = selected fields only, 'full' = all fields must match
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub snapshot_scope: Option<MasterSnapshotScope<'a>>,
    ///CID of the approved sprite blob (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub sprite_cid: Option<CowStr<'a>>,
    ///Snapshot of the player's stats for this system. Omitted when snapshotScope is 'none'.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub stats: Option<Data<'a>>,
    ///The stat system being validated (e.g. 'dnd', 'reverie', 'rmmz')
    #[serde(borrow)]
    pub system: CowStr<'a>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<Datetime>,
}

/// What portions of stats are validated. 'none' = inherent trust (always valid), 'custom' = selected fields only, 'full' = all fields must match

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum MasterSnapshotScope<'a> {
    None,
    Custom,
    Full,
    Other(CowStr<'a>),
}

impl<'a> MasterSnapshotScope<'a> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::None => "none",
            Self::Custom => "custom",
            Self::Full => "full",
            Self::Other(s) => s.as_ref(),
        }
    }
}

impl<'a> From<&'a str> for MasterSnapshotScope<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "none" => Self::None,
            "custom" => Self::Custom,
            "full" => Self::Full,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for MasterSnapshotScope<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "none" => Self::None,
            "custom" => Self::Custom,
            "full" => Self::Full,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> core::fmt::Display for MasterSnapshotScope<'a> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl<'a> AsRef<str> for MasterSnapshotScope<'a> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<'a> serde::Serialize for MasterSnapshotScope<'a> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de, 'a> serde::Deserialize<'de> for MasterSnapshotScope<'a>
where
    'de: 'a,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = <&'de str>::deserialize(deserializer)?;
        Ok(Self::from(s))
    }
}

impl<'a> Default for MasterSnapshotScope<'a> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl jacquard_common::IntoStatic for MasterSnapshotScope<'_> {
    type Output = MasterSnapshotScope<'static>;
    fn into_static(self) -> Self::Output {
        match self {
            MasterSnapshotScope::None => MasterSnapshotScope::None,
            MasterSnapshotScope::Custom => MasterSnapshotScope::Custom,
            MasterSnapshotScope::Full => MasterSnapshotScope::Full,
            MasterSnapshotScope::Other(v) => MasterSnapshotScope::Other(v.into_static()),
        }
    }
}

/// 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 MasterGetRecordOutput<'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: Master<'a>,
}

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

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

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

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

impl Collection for Master<'_> {
    const NSID: &'static str = "actor.rpg.master";
    type Record = MasterRecord;
}

impl Collection for MasterRecord {
    const NSID: &'static str = "actor.rpg.master";
    type Record = MasterRecord;
}

impl<'a> LexiconSchema for Master<'a> {
    fn nsid() -> &'static str {
        "actor.rpg.master"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_actor_rpg_master()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.campaign {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 100usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("campaign"),
                    max: 100usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.system;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 50usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("system"),
                    max: 50usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod master_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 System;
        type CreatedAt;
        type Player;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type System = Unset;
        type CreatedAt = Unset;
        type Player = Unset;
    }
    ///State transition - sets the `system` field to Set
    pub struct SetSystem<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetSystem<S> {}
    impl<S: State> State for SetSystem<S> {
        type System = Set<members::system>;
        type CreatedAt = S::CreatedAt;
        type Player = S::Player;
    }
    ///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 System = S::System;
        type CreatedAt = Set<members::created_at>;
        type Player = S::Player;
    }
    ///State transition - sets the `player` field to Set
    pub struct SetPlayer<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetPlayer<S> {}
    impl<S: State> State for SetPlayer<S> {
        type System = S::System;
        type CreatedAt = S::CreatedAt;
        type Player = Set<members::player>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `system` field
        pub struct system(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `player` field
        pub struct player(());
    }
}

/// Builder for constructing an instance of this type
pub struct MasterBuilder<'a, S: master_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<CowStr<'a>>,
        Option<Datetime>,
        Option<Did<'a>>,
        Option<MasterSnapshotScope<'a>>,
        Option<CowStr<'a>>,
        Option<Data<'a>>,
        Option<CowStr<'a>>,
        Option<Datetime>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Master<'a> {
    /// Create a new builder for this type
    pub fn new() -> MasterBuilder<'a, master_state::Empty> {
        MasterBuilder::new()
    }
}

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

impl<'a, S: master_state::State> MasterBuilder<'a, S> {
    /// Set the `campaign` field (optional)
    pub fn campaign(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `campaign` field to an Option value (optional)
    pub fn maybe_campaign(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.0 = value;
        self
    }
}

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

impl<'a, S> MasterBuilder<'a, S>
where
    S: master_state::State,
    S::Player: master_state::IsUnset,
{
    /// Set the `player` field (required)
    pub fn player(
        mut self,
        value: impl Into<Did<'a>>,
    ) -> MasterBuilder<'a, master_state::SetPlayer<S>> {
        self._fields.2 = Option::Some(value.into());
        MasterBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: master_state::State> MasterBuilder<'a, S> {
    /// Set the `snapshotScope` field (optional)
    pub fn snapshot_scope(
        mut self,
        value: impl Into<Option<MasterSnapshotScope<'a>>>,
    ) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `snapshotScope` field to an Option value (optional)
    pub fn maybe_snapshot_scope(
        mut self,
        value: Option<MasterSnapshotScope<'a>>,
    ) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<'a, S: master_state::State> MasterBuilder<'a, S> {
    /// Set the `spriteCid` field (optional)
    pub fn sprite_cid(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `spriteCid` field to an Option value (optional)
    pub fn maybe_sprite_cid(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<'a, S: master_state::State> MasterBuilder<'a, S> {
    /// Set the `stats` field (optional)
    pub fn stats(mut self, value: impl Into<Option<Data<'a>>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `stats` field to an Option value (optional)
    pub fn maybe_stats(mut self, value: Option<Data<'a>>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<'a, S> MasterBuilder<'a, S>
where
    S: master_state::State,
    S::System: master_state::IsUnset,
{
    /// Set the `system` field (required)
    pub fn system(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> MasterBuilder<'a, master_state::SetSystem<S>> {
        self._fields.6 = Option::Some(value.into());
        MasterBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: master_state::State> MasterBuilder<'a, S> {
    /// Set the `updatedAt` field (optional)
    pub fn updated_at(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `updatedAt` field to an Option value (optional)
    pub fn maybe_updated_at(mut self, value: Option<Datetime>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<'a, S> MasterBuilder<'a, S>
where
    S: master_state::State,
    S::System: master_state::IsSet,
    S::CreatedAt: master_state::IsSet,
    S::Player: master_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Master<'a> {
        Master {
            campaign: self._fields.0,
            created_at: self._fields.1.unwrap(),
            player: self._fields.2.unwrap(),
            snapshot_scope: self._fields.3,
            sprite_cid: self._fields.4,
            stats: self._fields.5,
            system: self._fields.6.unwrap(),
            updated_at: self._fields.7,
            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, Data<'a>>,
    ) -> Master<'a> {
        Master {
            campaign: self._fields.0,
            created_at: self._fields.1.unwrap(),
            player: self._fields.2.unwrap(),
            snapshot_scope: self._fields.3,
            sprite_cid: self._fields.4,
            stats: self._fields.5,
            system: self._fields.6.unwrap(),
            updated_at: self._fields.7,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_actor_rpg_master() -> 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("actor.rpg.master"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A master record validating one player's stats for one system. Multiple GMs can validate the same player.",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("player"),
                                SmolStr::new_static("system"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("campaign"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Name of the campaign this validation relates to",
                                        ),
                                    ),
                                    max_length: Some(100usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("player"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "DID of the player this record validates",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Did),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("snapshotScope"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "What portions of stats are validated. 'none' = inherent trust (always valid), 'custom' = selected fields only, 'full' = all fields must match",
                                        ),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("spriteCid"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "CID of the approved sprite blob (optional)",
                                        ),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("stats"),
                                LexObjectProperty::Unknown(LexUnknown {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("system"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The stat system being validated (e.g. 'dnd', 'reverie', 'rmmz')",
                                        ),
                                    ),
                                    max_length: Some(50usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("updatedAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}