// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: games.gamesgamesgamesgames.org.credit
//
// 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};
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::CompanyRole;
/// A relationship between a game and an organization.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "games.gamesgamesgamesgames.org.credit",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Credit<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<Datetime>,
    ///The name to be used if there is no profile associated with this credit, or the profile is inaccessible.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_name: Option<S>,
    ///The game to which this organization is being credited.
    pub game: StrongRef<S>,
    pub org: StrongRef<S>,
    pub roles: Vec<CompanyRole<S>>,
    #[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 CreditGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Credit<S>,
}

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

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

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

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

impl<S: BosStr> Collection for Credit<S> {
    const NSID: &'static str = "games.gamesgamesgamesgames.org.credit";
    type Record = CreditRecord;
}

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

impl<S: BosStr> LexiconSchema for Credit<S> {
    fn nsid() -> &'static str {
        "games.gamesgamesgamesgames.org.credit"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_games_gamesgamesgamesgames_org_credit()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.display_name {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 640usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("display_name"),
                    max: 640usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod credit_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 Game;
        type Org;
        type Roles;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Game = Unset;
        type Org = Unset;
        type Roles = Unset;
    }
    ///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 Game = Set<members::game>;
        type Org = St::Org;
        type Roles = St::Roles;
    }
    ///State transition - sets the `org` field to Set
    pub struct SetOrg<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetOrg<St> {}
    impl<St: State> State for SetOrg<St> {
        type Game = St::Game;
        type Org = Set<members::org>;
        type Roles = St::Roles;
    }
    ///State transition - sets the `roles` field to Set
    pub struct SetRoles<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetRoles<St> {}
    impl<St: State> State for SetRoles<St> {
        type Game = St::Game;
        type Org = St::Org;
        type Roles = Set<members::roles>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `game` field
        pub struct game(());
        ///Marker type for the `org` field
        pub struct org(());
        ///Marker type for the `roles` field
        pub struct roles(());
    }
}

/// Builder for constructing an instance of this type.
pub struct CreditBuilder<St: credit_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Datetime>,
        Option<S>,
        Option<StrongRef<S>>,
        Option<StrongRef<S>>,
        Option<Vec<CompanyRole<S>>>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> Credit<S> {
    /// Create a new builder for this type
    pub fn builder() -> CreditBuilder<credit_state::Empty, S> {
        CreditBuilder::builder()
    }
}

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

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

impl<St: credit_state::State, S: BosStr> CreditBuilder<St, S> {
    /// Set the `createdAt` field (optional)
    pub fn created_at(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `createdAt` field to an Option value (optional)
    pub fn maybe_created_at(mut self, value: Option<Datetime>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St: credit_state::State, S: BosStr> CreditBuilder<St, S> {
    /// Set the `displayName` field (optional)
    pub fn display_name(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `displayName` field to an Option value (optional)
    pub fn maybe_display_name(mut self, value: Option<S>) -> Self {
        self._fields.1 = value;
        self
    }
}

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

impl<St, S: BosStr> CreditBuilder<St, S>
where
    St: credit_state::State,
    St::Org: credit_state::IsUnset,
{
    /// Set the `org` field (required)
    pub fn org(
        mut self,
        value: impl Into<StrongRef<S>>,
    ) -> CreditBuilder<credit_state::SetOrg<St>, S> {
        self._fields.3 = Option::Some(value.into());
        CreditBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> CreditBuilder<St, S>
where
    St: credit_state::State,
    St::Roles: credit_state::IsUnset,
{
    /// Set the `roles` field (required)
    pub fn roles(
        mut self,
        value: impl Into<Vec<CompanyRole<S>>>,
    ) -> CreditBuilder<credit_state::SetRoles<St>, S> {
        self._fields.4 = Option::Some(value.into());
        CreditBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> CreditBuilder<St, S>
where
    St: credit_state::State,
    St::Game: credit_state::IsSet,
    St::Org: credit_state::IsSet,
    St::Roles: credit_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Credit<S> {
        Credit {
            created_at: self._fields.0,
            display_name: self._fields.1,
            game: self._fields.2.unwrap(),
            org: self._fields.3.unwrap(),
            roles: self._fields.4.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>>) -> Credit<S> {
        Credit {
            created_at: self._fields.0,
            display_name: self._fields.1,
            game: self._fields.2.unwrap(),
            org: self._fields.3.unwrap(),
            roles: self._fields.4.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_games_gamesgamesgamesgames_org_credit() -> 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.org.credit"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A relationship between a game and an organization.",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("org"), SmolStr::new_static("game"),
                                SmolStr::new_static("roles")
                            ],
                        ),
                        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("displayName"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The name to be used if there is no profile associated with this credit, or the profile is inaccessible.",
                                        ),
                                    ),
                                    max_length: Some(640usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("game"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("com.atproto.repo.strongRef"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("org"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("com.atproto.repo.strongRef"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("roles"),
                                LexObjectProperty::Array(LexArray {
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static(
                                            "games.gamesgamesgamesgames.defs#companyRole",
                                        ),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}