// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: games.gamesgamesgamesgames.contribution
//
// 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, Datetime};
use jacquard_common::types::uri::{RecordUri, UriError};
use jacquard_common::types::value::Data;
use jacquard_common::xrpc::XrpcResp;
use jacquard_derive::{IntoStatic, lexicon, open_union};
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::games_gamesgamesgamesgames::Signature;
/// A community contribution proposing changes to a game or submitting a new game.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "games.gamesgamesgamesgames.contribution",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Contribution<S: BosStr = DefaultStr> {
    ///A partial object matching the target record schema. Only changed fields are present.
    pub changes: Data<S>,
    pub contribution_type: ContributionContributionType<S>,
    pub created_at: Datetime,
    ///Explanation of what is being changed and why.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<S>,
    ///Inline attestation signatures from the AppView that created this contribution.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signatures: Option<Vec<ContributionSignaturesItem<S>>>,
    ///The entity being modified. Required for corrections and additions, absent for new game submissions.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subject: Option<AtUri<S>>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ContributionContributionType<S: BosStr = DefaultStr> {
    Correction,
    Addition,
    NewGame,
    Other(S),
}

impl<S: BosStr> ContributionContributionType<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Correction => "correction",
            Self::Addition => "addition",
            Self::NewGame => "newGame",
            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() {
            "correction" => Self::Correction,
            "addition" => Self::Addition,
            "newGame" => Self::NewGame,
            _ => Self::Other(s),
        }
    }
}

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

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

impl<S: BosStr> Serialize for ContributionContributionType<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 ContributionContributionType<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 ContributionContributionType<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for ContributionContributionType<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = ContributionContributionType<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            ContributionContributionType::Correction => {
                ContributionContributionType::Correction
            }
            ContributionContributionType::Addition => {
                ContributionContributionType::Addition
            }
            ContributionContributionType::NewGame => {
                ContributionContributionType::NewGame
            }
            ContributionContributionType::Other(v) => {
                ContributionContributionType::Other(v.into_static())
            }
        }
    }
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub enum ContributionSignaturesItem<S: BosStr = DefaultStr> {
    #[serde(rename = "games.gamesgamesgamesgames.defs#signature")]
    Signature(Box<Signature<S>>),
    #[serde(rename = "com.atproto.repo.strongRef")]
    StrongRef(Box<StrongRef<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 ContributionGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Contribution<S>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct ContributionRecord;
impl XrpcResp for ContributionRecord {
    const NSID: &'static str = "games.gamesgamesgamesgames.contribution";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = ContributionGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Contribution<S> {
    const NSID: &'static str = "games.gamesgamesgamesgames.contribution";
    type Record = ContributionRecord;
}

impl Collection for ContributionRecord {
    const NSID: &'static str = "games.gamesgamesgamesgames.contribution";
    type Record = ContributionRecord;
}

impl<S: BosStr> LexiconSchema for Contribution<S> {
    fn nsid() -> &'static str {
        "games.gamesgamesgamesgames.contribution"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_games_gamesgamesgamesgames_contribution()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.message {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 3000usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("message"),
                        max: 3000usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

pub mod contribution_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 Changes;
        type ContributionType;
        type CreatedAt;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Changes = Unset;
        type ContributionType = Unset;
        type CreatedAt = Unset;
    }
    ///State transition - sets the `changes` field to Set
    pub struct SetChanges<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetChanges<St> {}
    impl<St: State> State for SetChanges<St> {
        type Changes = Set<members::changes>;
        type ContributionType = St::ContributionType;
        type CreatedAt = St::CreatedAt;
    }
    ///State transition - sets the `contribution_type` field to Set
    pub struct SetContributionType<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetContributionType<St> {}
    impl<St: State> State for SetContributionType<St> {
        type Changes = St::Changes;
        type ContributionType = Set<members::contribution_type>;
        type CreatedAt = St::CreatedAt;
    }
    ///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 Changes = St::Changes;
        type ContributionType = St::ContributionType;
        type CreatedAt = Set<members::created_at>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `changes` field
        pub struct changes(());
        ///Marker type for the `contribution_type` field
        pub struct contribution_type(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
    }
}

/// Builder for constructing an instance of this type.
pub struct ContributionBuilder<St: contribution_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Data<S>>,
        Option<ContributionContributionType<S>>,
        Option<Datetime>,
        Option<S>,
        Option<Vec<ContributionSignaturesItem<S>>>,
        Option<AtUri<S>>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> Contribution<S> {
    /// Create a new builder for this type
    pub fn builder() -> ContributionBuilder<contribution_state::Empty, S> {
        ContributionBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> ContributionBuilder<St, S>
where
    St: contribution_state::State,
    St::Changes: contribution_state::IsUnset,
{
    /// Set the `changes` field (required)
    pub fn changes(
        mut self,
        value: impl Into<Data<S>>,
    ) -> ContributionBuilder<contribution_state::SetChanges<St>, S> {
        self._fields.0 = Option::Some(value.into());
        ContributionBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ContributionBuilder<St, S>
where
    St: contribution_state::State,
    St::ContributionType: contribution_state::IsUnset,
{
    /// Set the `contributionType` field (required)
    pub fn contribution_type(
        mut self,
        value: impl Into<ContributionContributionType<S>>,
    ) -> ContributionBuilder<contribution_state::SetContributionType<St>, S> {
        self._fields.1 = Option::Some(value.into());
        ContributionBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

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

impl<St: contribution_state::State, S: BosStr> ContributionBuilder<St, S> {
    /// Set the `message` field (optional)
    pub fn message(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `message` field to an Option value (optional)
    pub fn maybe_message(mut self, value: Option<S>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St: contribution_state::State, S: BosStr> ContributionBuilder<St, S> {
    /// Set the `signatures` field (optional)
    pub fn signatures(
        mut self,
        value: impl Into<Option<Vec<ContributionSignaturesItem<S>>>>,
    ) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `signatures` field to an Option value (optional)
    pub fn maybe_signatures(
        mut self,
        value: Option<Vec<ContributionSignaturesItem<S>>>,
    ) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St: contribution_state::State, S: BosStr> ContributionBuilder<St, S> {
    /// Set the `subject` field (optional)
    pub fn subject(mut self, value: impl Into<Option<AtUri<S>>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `subject` field to an Option value (optional)
    pub fn maybe_subject(mut self, value: Option<AtUri<S>>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<St, S: BosStr> ContributionBuilder<St, S>
where
    St: contribution_state::State,
    St::Changes: contribution_state::IsSet,
    St::ContributionType: contribution_state::IsSet,
    St::CreatedAt: contribution_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Contribution<S> {
        Contribution {
            changes: self._fields.0.unwrap(),
            contribution_type: self._fields.1.unwrap(),
            created_at: self._fields.2.unwrap(),
            message: self._fields.3,
            signatures: self._fields.4,
            subject: self._fields.5,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(
        self,
        extra_data: BTreeMap<SmolStr, Data<S>>,
    ) -> Contribution<S> {
        Contribution {
            changes: self._fields.0.unwrap(),
            contribution_type: self._fields.1.unwrap(),
            created_at: self._fields.2.unwrap(),
            message: self._fields.3,
            signatures: self._fields.4,
            subject: self._fields.5,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_games_gamesgamesgamesgames_contribution() -> 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("games.gamesgamesgamesgames.contribution"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A community contribution proposing changes to a game or submitting a new game.",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("contributionType"),
                                SmolStr::new_static("changes"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("changes"),
                                LexObjectProperty::Unknown(LexUnknown {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("contributionType"),
                                LexObjectProperty::String(LexString {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("message"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Explanation of what is being changed and why.",
                                        ),
                                    ),
                                    max_graphemes: Some(3000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("signatures"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Inline attestation signatures from the AppView that created this contribution.",
                                        ),
                                    ),
                                    items: LexArrayItem::Union(LexRefUnion {
                                        refs: vec![
                                            CowStr::new_static("games.gamesgamesgamesgames.defs#signature"),
                                            CowStr::new_static("com.atproto.repo.strongRef")
                                        ],
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("subject"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The entity being modified. Required for corrections and additions, absent for new game submissions.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::AtUri),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}