// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: social.psky.chat.room
//
// 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, Language};
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::social_psky::chat::room;
/// A Picosky room belonging to the user.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "social.psky.chat.room",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Room<S: BosStr = DefaultStr> {
    ///List of users allowed to send messages in the room.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allowlist: Option<room::ModlistRef<S>>,
    ///List of users disallowed to send messages in the room.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub denylist: Option<room::ModlistRef<S>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub languages: Option<Vec<Language>>,
    pub name: S,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<S>>,
    ///Topic title of the room.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub topic: Option<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 RoomGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Room<S>,
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct ModlistRef<S: BosStr = DefaultStr> {
    /// Defaults to `false`.
    #[serde(default = "_default_modlist_ref_active")]
    pub active: bool,
    pub users: Vec<Did<S>>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct RoomRecord;
impl XrpcResp for RoomRecord {
    const NSID: &'static str = "social.psky.chat.room";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = RoomGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Room<S> {
    const NSID: &'static str = "social.psky.chat.room";
    type Record = RoomRecord;
}

impl Collection for RoomRecord {
    const NSID: &'static str = "social.psky.chat.room";
    type Record = RoomRecord;
}

impl<S: BosStr> LexiconSchema for Room<S> {
    fn nsid() -> &'static str {
        "social.psky.chat.room"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_social_psky_chat_room()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.languages {
            #[allow(unused_comparisons)]
            if value.len() > 3usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("languages"),
                    max: 3usize,
                    actual: value.len(),
                });
            }
        }
        {
            let value = &self.name;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 320usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("name"),
                    max: 320usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.name;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 32usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("name"),
                        max: 32usize,
                        actual: count,
                    });
                }
            }
        }
        if let Some(ref value) = self.tags {
            #[allow(unused_comparisons)]
            if value.len() > 20usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("tags"),
                    max: 20usize,
                    actual: value.len(),
                });
            }
        }
        if let Some(ref value) = self.topic {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 2560usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("topic"),
                    max: 2560usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.topic {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 256usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("topic"),
                        max: 256usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for ModlistRef<S> {
    fn nsid() -> &'static str {
        "social.psky.chat.room"
    }
    fn def_name() -> &'static str {
        "modlistRef"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_social_psky_chat_room()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

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

/// Builder for constructing an instance of this type.
pub struct RoomBuilder<St: room_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<room::ModlistRef<S>>,
        Option<room::ModlistRef<S>>,
        Option<Vec<Language>>,
        Option<S>,
        Option<Vec<S>>,
        Option<S>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> Room<S> {
    /// Create a new builder for this type
    pub fn builder() -> RoomBuilder<room_state::Empty, S> {
        RoomBuilder::builder()
    }
}

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

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

impl<St: room_state::State, S: BosStr> RoomBuilder<St, S> {
    /// Set the `allowlist` field (optional)
    pub fn allowlist(mut self, value: impl Into<Option<room::ModlistRef<S>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `allowlist` field to an Option value (optional)
    pub fn maybe_allowlist(mut self, value: Option<room::ModlistRef<S>>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St: room_state::State, S: BosStr> RoomBuilder<St, S> {
    /// Set the `denylist` field (optional)
    pub fn denylist(mut self, value: impl Into<Option<room::ModlistRef<S>>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `denylist` field to an Option value (optional)
    pub fn maybe_denylist(mut self, value: Option<room::ModlistRef<S>>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<St: room_state::State, S: BosStr> RoomBuilder<St, S> {
    /// Set the `languages` field (optional)
    pub fn languages(mut self, value: impl Into<Option<Vec<Language>>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `languages` field to an Option value (optional)
    pub fn maybe_languages(mut self, value: Option<Vec<Language>>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<St, S: BosStr> RoomBuilder<St, S>
where
    St: room_state::State,
    St::Name: room_state::IsUnset,
{
    /// Set the `name` field (required)
    pub fn name(
        mut self,
        value: impl Into<S>,
    ) -> RoomBuilder<room_state::SetName<St>, S> {
        self._fields.3 = Option::Some(value.into());
        RoomBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

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

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

impl<St, S: BosStr> RoomBuilder<St, S>
where
    St: room_state::State,
    St::Name: room_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Room<S> {
        Room {
            allowlist: self._fields.0,
            denylist: self._fields.1,
            languages: self._fields.2,
            name: self._fields.3.unwrap(),
            tags: self._fields.4,
            topic: 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>>) -> Room<S> {
        Room {
            allowlist: self._fields.0,
            denylist: self._fields.1,
            languages: self._fields.2,
            name: self._fields.3.unwrap(),
            tags: self._fields.4,
            topic: self._fields.5,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_social_psky_chat_room() -> 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("social.psky.chat.room"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static("A Picosky room belonging to the user."),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(vec![SmolStr::new_static("name")]),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("allowlist"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("#modlistRef"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("denylist"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("#modlistRef"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("languages"),
                                LexObjectProperty::Array(LexArray {
                                    items: LexArrayItem::String(LexString {
                                        format: Some(LexStringFormat::Language),
                                        ..Default::default()
                                    }),
                                    max_length: Some(3usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("name"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(320usize),
                                    max_graphemes: Some(32usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("tags"),
                                LexObjectProperty::Array(LexArray {
                                    items: LexArrayItem::String(LexString {
                                        ..Default::default()
                                    }),
                                    max_length: Some(20usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("topic"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Topic title of the room."),
                                    ),
                                    max_length: Some(2560usize),
                                    max_graphemes: Some(256usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("modlistRef"),
                LexUserType::Object(LexObject {
                    required: Some(
                        vec![SmolStr::new_static("active"), SmolStr::new_static("users")],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("active"),
                            LexObjectProperty::Boolean(LexBoolean {
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("users"),
                            LexObjectProperty::Array(LexArray {
                                items: LexArrayItem::String(LexString {
                                    format: Some(LexStringFormat::Did),
                                    ..Default::default()
                                }),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

fn _default_modlist_ref_active() -> bool {
    false
}

pub mod modlist_ref_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 Active;
        type Users;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Active = Unset;
        type Users = Unset;
    }
    ///State transition - sets the `active` field to Set
    pub struct SetActive<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetActive<St> {}
    impl<St: State> State for SetActive<St> {
        type Active = Set<members::active>;
        type Users = St::Users;
    }
    ///State transition - sets the `users` field to Set
    pub struct SetUsers<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetUsers<St> {}
    impl<St: State> State for SetUsers<St> {
        type Active = St::Active;
        type Users = Set<members::users>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `active` field
        pub struct active(());
        ///Marker type for the `users` field
        pub struct users(());
    }
}

/// Builder for constructing an instance of this type.
pub struct ModlistRefBuilder<St: modlist_ref_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (Option<bool>, Option<Vec<Did<S>>>),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> ModlistRef<S> {
    /// Create a new builder for this type
    pub fn builder() -> ModlistRefBuilder<modlist_ref_state::Empty, S> {
        ModlistRefBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> ModlistRefBuilder<St, S>
where
    St: modlist_ref_state::State,
    St::Active: modlist_ref_state::IsUnset,
{
    /// Set the `active` field (required)
    pub fn active(
        mut self,
        value: impl Into<bool>,
    ) -> ModlistRefBuilder<modlist_ref_state::SetActive<St>, S> {
        self._fields.0 = Option::Some(value.into());
        ModlistRefBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ModlistRefBuilder<St, S>
where
    St: modlist_ref_state::State,
    St::Users: modlist_ref_state::IsUnset,
{
    /// Set the `users` field (required)
    pub fn users(
        mut self,
        value: impl Into<Vec<Did<S>>>,
    ) -> ModlistRefBuilder<modlist_ref_state::SetUsers<St>, S> {
        self._fields.1 = Option::Some(value.into());
        ModlistRefBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ModlistRefBuilder<St, S>
where
    St: modlist_ref_state::State,
    St::Active: modlist_ref_state::IsSet,
    St::Users: modlist_ref_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> ModlistRef<S> {
        ModlistRef {
            active: self._fields.0.unwrap(),
            users: self._fields.1.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>>,
    ) -> ModlistRef<S> {
        ModlistRef {
            active: self._fields.0.unwrap(),
            users: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}