// @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;

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
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::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.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Room<'a> {
    ///List of users allowed to send messages in the room.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub allowlist: Option<room::ModlistRef<'a>>,
    ///List of users disallowed to send messages in the room.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub denylist: Option<room::ModlistRef<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub languages: Option<Vec<Language>>,
    #[serde(borrow)]
    pub name: CowStr<'a>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub tags: Option<Vec<CowStr<'a>>>,
    ///Topic title of the room.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub topic: Option<CowStr<'a>>,
}

/// 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<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub cid: Option<Cid<'a>>,
    #[serde(borrow)]
    pub uri: AtUri<'a>,
    #[serde(borrow)]
    pub value: Room<'a>,
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct ModlistRef<'a> {
    /// Defaults to `false`.
    #[serde(default = "_default_modlist_ref_active")]
    pub active: bool,
    #[serde(borrow)]
    pub users: Vec<Did<'a>>,
}

impl<'a> Room<'a> {
    pub fn uri(
        uri: impl Into<CowStr<'a>>,
    ) -> Result<RecordUri<'a, RoomRecord>, UriError> {
        RecordUri::try_from_uri(AtUri::new_cow(uri.into())?)
    }
}

/// 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<'de> = RoomGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

impl From<RoomGetRecordOutput<'_>> for Room<'_> {
    fn from(output: RoomGetRecordOutput<'_>) -> Self {
        use jacquard_common::IntoStatic;
        output.value.into_static()
    }
}

impl Collection for Room<'_> {
    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<'a> LexiconSchema for Room<'a> {
    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<'a> LexiconSchema for ModlistRef<'a> {
    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<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetName<S> {}
    impl<S: State> State for SetName<S> {
        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<'a, S: room_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<room::ModlistRef<'a>>,
        Option<room::ModlistRef<'a>>,
        Option<Vec<Language>>,
        Option<CowStr<'a>>,
        Option<Vec<CowStr<'a>>>,
        Option<CowStr<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

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

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

impl<'a, S: room_state::State> RoomBuilder<'a, S> {
    /// Set the `allowlist` field (optional)
    pub fn allowlist(mut self, value: impl Into<Option<room::ModlistRef<'a>>>) -> 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<'a>>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<'a, S: room_state::State> RoomBuilder<'a, S> {
    /// Set the `denylist` field (optional)
    pub fn denylist(mut self, value: impl Into<Option<room::ModlistRef<'a>>>) -> 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<'a>>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<'a, S: room_state::State> RoomBuilder<'a, 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<'a, S> RoomBuilder<'a, S>
where
    S: room_state::State,
    S::Name: room_state::IsUnset,
{
    /// Set the `name` field (required)
    pub fn name(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> RoomBuilder<'a, room_state::SetName<S>> {
        self._fields.3 = Option::Some(value.into());
        RoomBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: room_state::State> RoomBuilder<'a, S> {
    /// Set the `tags` field (optional)
    pub fn tags(mut self, value: impl Into<Option<Vec<CowStr<'a>>>>) -> 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<CowStr<'a>>>) -> Self {
        self._fields.4 = value;
        self
    }
}

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

impl<'a, S> RoomBuilder<'a, S>
where
    S: room_state::State,
    S::Name: room_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Room<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Room<'a> {
        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<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetActive<S> {}
    impl<S: State> State for SetActive<S> {
        type Active = Set<members::active>;
        type Users = S::Users;
    }
    ///State transition - sets the `users` field to Set
    pub struct SetUsers<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetUsers<S> {}
    impl<S: State> State for SetUsers<S> {
        type Active = S::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<'a, S: modlist_ref_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (Option<bool>, Option<Vec<Did<'a>>>),
    _lifetime: PhantomData<&'a ()>,
}

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

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

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

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

impl<'a, S> ModlistRefBuilder<'a, S>
where
    S: modlist_ref_state::State,
    S::Active: modlist_ref_state::IsSet,
    S::Users: modlist_ref_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> ModlistRef<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> ModlistRef<'a> {
        ModlistRef {
            active: self._fields.0.unwrap(),
            users: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}