// @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, 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};
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.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "actor.rpg.master",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Master<S: BosStr = DefaultStr> {
    ///Name of the campaign this validation relates to
    #[serde(skip_serializing_if = "Option::is_none")]
    pub campaign: Option<S>,
    pub created_at: Datetime,
    ///DID of the player this record validates
    pub player: Did<S>,
    ///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")]
    pub snapshot_scope: Option<MasterSnapshotScope<S>>,
    ///CID of the approved sprite blob (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sprite_cid: Option<S>,
    ///Snapshot of the player's stats for this system. Omitted when snapshotScope is 'none'.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stats: Option<Data<S>>,
    ///The stat system being validated (e.g. 'dnd', 'reverie', 'rmmz')
    pub system: S,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<Datetime>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// 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<S: BosStr = DefaultStr> {
    None,
    Custom,
    Full,
    Other(S),
}

impl<S: BosStr> MasterSnapshotScope<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::None => "none",
            Self::Custom => "custom",
            Self::Full => "full",
            Self::Other(s) => s.as_ref(),
        }
    }
    /// Construct from a string-like value, matching known values.
    pub fn from_value(s: S) -> Self {
        match s.as_ref() {
            "none" => Self::None,
            "custom" => Self::Custom,
            "full" => Self::Full,
            _ => Self::Other(s),
        }
    }
}

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

impl<S: BosStr> AsRef<str> for MasterSnapshotScope<S> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

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

impl<'de, S: Deserialize<'de> + BosStr> Deserialize<'de> for MasterSnapshotScope<S> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = S::deserialize(deserializer)?;
        Ok(Self::from_value(s))
    }
}

impl<S: BosStr + Default> Default for MasterSnapshotScope<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for MasterSnapshotScope<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = MasterSnapshotScope<S::Output>;
    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<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Master<S>,
}

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

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

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

impl<S: BosStr> Collection for Master<S> {
    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<S: BosStr> LexiconSchema for Master<S> {
    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 CreatedAt;
        type Player;
        type System;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedAt = Unset;
        type Player = Unset;
        type System = 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 Player = St::Player;
        type System = St::System;
    }
    ///State transition - sets the `player` field to Set
    pub struct SetPlayer<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetPlayer<St> {}
    impl<St: State> State for SetPlayer<St> {
        type CreatedAt = St::CreatedAt;
        type Player = Set<members::player>;
        type System = St::System;
    }
    ///State transition - sets the `system` field to Set
    pub struct SetSystem<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetSystem<St> {}
    impl<St: State> State for SetSystem<St> {
        type CreatedAt = St::CreatedAt;
        type Player = St::Player;
        type System = Set<members::system>;
    }
    /// 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 `player` field
        pub struct player(());
        ///Marker type for the `system` field
        pub struct system(());
    }
}

/// Builder for constructing an instance of this type.
pub struct MasterBuilder<St: master_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<S>,
        Option<Datetime>,
        Option<Did<S>>,
        Option<MasterSnapshotScope<S>>,
        Option<S>,
        Option<Data<S>>,
        Option<S>,
        Option<Datetime>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

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

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

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

impl<St: master_state::State, S: BosStr> MasterBuilder<St, S> {
    /// Set the `snapshotScope` field (optional)
    pub fn snapshot_scope(
        mut self,
        value: impl Into<Option<MasterSnapshotScope<S>>>,
    ) -> 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<S>>,
    ) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St: master_state::State, S: BosStr> MasterBuilder<St, S> {
    /// Set the `spriteCid` field (optional)
    pub fn sprite_cid(mut self, value: impl Into<Option<S>>) -> 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<S>) -> Self {
        self._fields.4 = value;
        self
    }
}

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

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

impl<St: master_state::State, S: BosStr> MasterBuilder<St, 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<St, S: BosStr> MasterBuilder<St, S>
where
    St: master_state::State,
    St::CreatedAt: master_state::IsSet,
    St::Player: master_state::IsSet,
    St::System: master_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Master<S> {
        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<SmolStr, Data<S>>) -> Master<S> {
        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()
    }
}