// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: games.gamesgamesgamesgames.actor.game
//
// 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;
use crate::games_gamesgamesgamesgames::actor::game;
/// Reference to a game, either by AT URI or external platform ID.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct GameRef<S: BosStr = DefaultStr> {
    ///External platform's ID for the game.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub external_id: Option<S>,
    ///External platform for ID lookup.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub platform: Option<S>,
    ///AT URI of the game record.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uri: Option<AtUri<S>>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// A record indicating the actor owns a game on a specific platform. May include attestation signatures proving ownership was verified by an external service.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "games.gamesgamesgamesgames.actor.game",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Game<S: BosStr = DefaultStr> {
    pub created_at: Datetime,
    ///Reference to the game record.
    pub game: game::GameRef<S>,
    ///The platform where ownership was verified.
    pub platform: GamePlatform<S>,
    ///Attestation signatures proving ownership was verified. Can be inline signatures or strongRefs to remote proof records.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signatures: Option<Vec<GameSignaturesItem<S>>>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// The platform where ownership was verified.

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum GamePlatform<S: BosStr = DefaultStr> {
    Steam,
    Gog,
    Epic,
    Playstation,
    Xbox,
    Nintendo,
    Itchio,
    Humble,
    Other(S),
}

impl<S: BosStr> GamePlatform<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Steam => "steam",
            Self::Gog => "gog",
            Self::Epic => "epic",
            Self::Playstation => "playstation",
            Self::Xbox => "xbox",
            Self::Nintendo => "nintendo",
            Self::Itchio => "itchio",
            Self::Humble => "humble",
            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() {
            "steam" => Self::Steam,
            "gog" => Self::Gog,
            "epic" => Self::Epic,
            "playstation" => Self::Playstation,
            "xbox" => Self::Xbox,
            "nintendo" => Self::Nintendo,
            "itchio" => Self::Itchio,
            "humble" => Self::Humble,
            _ => Self::Other(s),
        }
    }
}

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

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

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

impl<S: BosStr> jacquard_common::IntoStatic for GamePlatform<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = GamePlatform<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            GamePlatform::Steam => GamePlatform::Steam,
            GamePlatform::Gog => GamePlatform::Gog,
            GamePlatform::Epic => GamePlatform::Epic,
            GamePlatform::Playstation => GamePlatform::Playstation,
            GamePlatform::Xbox => GamePlatform::Xbox,
            GamePlatform::Nintendo => GamePlatform::Nintendo,
            GamePlatform::Itchio => GamePlatform::Itchio,
            GamePlatform::Humble => GamePlatform::Humble,
            GamePlatform::Other(v) => GamePlatform::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 GameSignaturesItem<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 GameGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Game<S>,
}

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

impl<S: BosStr> LexiconSchema for GameRef<S> {
    fn nsid() -> &'static str {
        "games.gamesgamesgamesgames.actor.game"
    }
    fn def_name() -> &'static str {
        "gameRef"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_games_gamesgamesgamesgames_actor_game()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

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

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

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

impl<S: BosStr> Collection for Game<S> {
    const NSID: &'static str = "games.gamesgamesgamesgames.actor.game";
    type Record = GameRecord;
}

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

impl<S: BosStr> LexiconSchema for Game<S> {
    fn nsid() -> &'static str {
        "games.gamesgamesgamesgames.actor.game"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_games_gamesgamesgamesgames_actor_game()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

fn lexicon_doc_games_gamesgamesgamesgames_actor_game() -> 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.actor.game"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("gameRef"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "Reference to a game, either by AT URI or external platform ID.",
                        ),
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("externalId"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("External platform's ID for the game."),
                                ),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("platform"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("External platform for ID lookup."),
                                ),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("uri"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("AT URI of the game record."),
                                ),
                                format: Some(LexStringFormat::AtUri),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A record indicating the actor owns a game on a specific platform. May include attestation signatures proving ownership was verified by an external service.",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("game"),
                                SmolStr::new_static("platform"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("game"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("#gameRef"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("platform"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The platform where ownership was verified.",
                                        ),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("signatures"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Attestation signatures proving ownership was verified. Can be inline signatures or strongRefs to remote proof records.",
                                        ),
                                    ),
                                    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
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod game_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 Game;
        type Platform;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedAt = Unset;
        type Game = Unset;
        type Platform = 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 Game = St::Game;
        type Platform = St::Platform;
    }
    ///State transition - sets the `game` field to Set
    pub struct SetGame<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetGame<St> {}
    impl<St: State> State for SetGame<St> {
        type CreatedAt = St::CreatedAt;
        type Game = Set<members::game>;
        type Platform = St::Platform;
    }
    ///State transition - sets the `platform` field to Set
    pub struct SetPlatform<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetPlatform<St> {}
    impl<St: State> State for SetPlatform<St> {
        type CreatedAt = St::CreatedAt;
        type Game = St::Game;
        type Platform = Set<members::platform>;
    }
    /// 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 `game` field
        pub struct game(());
        ///Marker type for the `platform` field
        pub struct platform(());
    }
}

/// Builder for constructing an instance of this type.
pub struct GameBuilder<St: game_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Datetime>,
        Option<game::GameRef<S>>,
        Option<GamePlatform<S>>,
        Option<Vec<GameSignaturesItem<S>>>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> Game<S> {
    /// Create a new builder for this type
    pub fn builder() -> GameBuilder<game_state::Empty, S> {
        GameBuilder::builder()
    }
}

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

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

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

impl<St, S: BosStr> GameBuilder<St, S>
where
    St: game_state::State,
    St::Game: game_state::IsUnset,
{
    /// Set the `game` field (required)
    pub fn game(
        mut self,
        value: impl Into<game::GameRef<S>>,
    ) -> GameBuilder<game_state::SetGame<St>, S> {
        self._fields.1 = Option::Some(value.into());
        GameBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> GameBuilder<St, S>
where
    St: game_state::State,
    St::Platform: game_state::IsUnset,
{
    /// Set the `platform` field (required)
    pub fn platform(
        mut self,
        value: impl Into<GamePlatform<S>>,
    ) -> GameBuilder<game_state::SetPlatform<St>, S> {
        self._fields.2 = Option::Some(value.into());
        GameBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

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

impl<St, S: BosStr> GameBuilder<St, S>
where
    St: game_state::State,
    St::CreatedAt: game_state::IsSet,
    St::Game: game_state::IsSet,
    St::Platform: game_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Game<S> {
        Game {
            created_at: self._fields.0.unwrap(),
            game: self._fields.1.unwrap(),
            platform: self._fields.2.unwrap(),
            signatures: self._fields.3,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(self, extra_data: BTreeMap<SmolStr, Data<S>>) -> Game<S> {
        Game {
            created_at: self._fields.0.unwrap(),
            game: self._fields.1.unwrap(),
            platform: self._fields.2.unwrap(),
            signatures: self._fields.3,
            extra_data: Some(extra_data),
        }
    }
}