// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: blue.atroom.room.object
//
// 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::blob::BlobRef;
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::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::blue_atroom::room::object;

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct LocalizedName<'a> {
    #[serde(borrow)]
    pub lang: CowStr<'a>,
    #[serde(borrow)]
    pub value: CowStr<'a>,
}

/// A 3D object that can be placed in a room.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Object<'a> {
    pub created_at: Datetime,
    #[serde(borrow)]
    pub model: BlobRef<'a>,
    #[serde(borrow)]
    pub name: CowStr<'a>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub name_langs: Option<Vec<object::LocalizedName<'a>>>,
    pub scale: i64,
}

/// 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 ObjectGetRecordOutput<'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: Object<'a>,
}

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

impl<'a> LexiconSchema for LocalizedName<'a> {
    fn nsid() -> &'static str {
        "blue.atroom.room.object"
    }
    fn def_name() -> &'static str {
        "localizedName"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_blue_atroom_room_object()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.lang;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 16usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("lang"),
                    max: 16usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.value;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 100usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("value"),
                    max: 100usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

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

#[derive(Debug, Serialize, Deserialize)]
pub struct ObjectRecord;
impl XrpcResp for ObjectRecord {
    const NSID: &'static str = "blue.atroom.room.object";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = ObjectGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Object<'_> {
    const NSID: &'static str = "blue.atroom.room.object";
    type Record = ObjectRecord;
}

impl Collection for ObjectRecord {
    const NSID: &'static str = "blue.atroom.room.object";
    type Record = ObjectRecord;
}

impl<'a> LexiconSchema for Object<'a> {
    fn nsid() -> &'static str {
        "blue.atroom.room.object"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_blue_atroom_room_object()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.model;
            {
                let size = value.blob().size;
                if size > 10485760usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("model"),
                        max: 10485760usize,
                        actual: size,
                    });
                }
            }
        }
        {
            let value = &self.model;
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &["model/gltf-binary"];
                let matched = accepted
                    .iter()
                    .any(|pattern| {
                        if *pattern == "*/*" {
                            true
                        } else if pattern.ends_with("/*") {
                            let prefix = &pattern[..pattern.len() - 2];
                            mime.starts_with(prefix)
                                && mime.as_bytes().get(prefix.len()) == Some(&b'/')
                        } else {
                            mime == *pattern
                        }
                    });
                if !matched {
                    return Err(ConstraintError::BlobMimeTypeNotAccepted {
                        path: ValidationPath::from_field("model"),
                        accepted: vec!["model/gltf-binary".to_string()],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        {
            let value = &self.name;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 100usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("name"),
                    max: 100usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.scale;
            if *value > 1000i64 {
                return Err(ConstraintError::Maximum {
                    path: ValidationPath::from_field("scale"),
                    max: 1000i64,
                    actual: *value,
                });
            }
        }
        {
            let value = &self.scale;
            if *value < 1i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("scale"),
                    min: 1i64,
                    actual: *value,
                });
            }
        }
        Ok(())
    }
}

fn lexicon_doc_blue_atroom_room_object() -> 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("blue.atroom.room.object"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("localizedName"),
                LexUserType::Object(LexObject {
                    required: Some(
                        vec![SmolStr::new_static("lang"), SmolStr::new_static("value")],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("lang"),
                            LexObjectProperty::String(LexString {
                                max_length: Some(16usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("value"),
                            LexObjectProperty::String(LexString {
                                max_length: Some(100usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static("A 3D object that can be placed in a room."),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("name"), SmolStr::new_static("model"),
                                SmolStr::new_static("scale"),
                                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("model"),
                                LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                            );
                            map.insert(
                                SmolStr::new_static("name"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(100usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("nameLangs"),
                                LexObjectProperty::Array(LexArray {
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#localizedName"),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("scale"),
                                LexObjectProperty::Integer(LexInteger {
                                    minimum: Some(1i64),
                                    maximum: Some(1000i64),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod object_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 Scale;
        type Name;
        type CreatedAt;
        type Model;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Scale = Unset;
        type Name = Unset;
        type CreatedAt = Unset;
        type Model = Unset;
    }
    ///State transition - sets the `scale` field to Set
    pub struct SetScale<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetScale<S> {}
    impl<S: State> State for SetScale<S> {
        type Scale = Set<members::scale>;
        type Name = S::Name;
        type CreatedAt = S::CreatedAt;
        type Model = S::Model;
    }
    ///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 Scale = S::Scale;
        type Name = Set<members::name>;
        type CreatedAt = S::CreatedAt;
        type Model = S::Model;
    }
    ///State transition - sets the `created_at` field to Set
    pub struct SetCreatedAt<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetCreatedAt<S> {}
    impl<S: State> State for SetCreatedAt<S> {
        type Scale = S::Scale;
        type Name = S::Name;
        type CreatedAt = Set<members::created_at>;
        type Model = S::Model;
    }
    ///State transition - sets the `model` field to Set
    pub struct SetModel<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetModel<S> {}
    impl<S: State> State for SetModel<S> {
        type Scale = S::Scale;
        type Name = S::Name;
        type CreatedAt = S::CreatedAt;
        type Model = Set<members::model>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `scale` field
        pub struct scale(());
        ///Marker type for the `name` field
        pub struct name(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `model` field
        pub struct model(());
    }
}

/// Builder for constructing an instance of this type
pub struct ObjectBuilder<'a, S: object_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Datetime>,
        Option<BlobRef<'a>>,
        Option<CowStr<'a>>,
        Option<Vec<object::LocalizedName<'a>>>,
        Option<i64>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Object<'a> {
    /// Create a new builder for this type
    pub fn new() -> ObjectBuilder<'a, object_state::Empty> {
        ObjectBuilder::new()
    }
}

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

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

impl<'a, S> ObjectBuilder<'a, S>
where
    S: object_state::State,
    S::Model: object_state::IsUnset,
{
    /// Set the `model` field (required)
    pub fn model(
        mut self,
        value: impl Into<BlobRef<'a>>,
    ) -> ObjectBuilder<'a, object_state::SetModel<S>> {
        self._fields.1 = Option::Some(value.into());
        ObjectBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> ObjectBuilder<'a, S>
where
    S: object_state::State,
    S::Name: object_state::IsUnset,
{
    /// Set the `name` field (required)
    pub fn name(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> ObjectBuilder<'a, object_state::SetName<S>> {
        self._fields.2 = Option::Some(value.into());
        ObjectBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: object_state::State> ObjectBuilder<'a, S> {
    /// Set the `nameLangs` field (optional)
    pub fn name_langs(
        mut self,
        value: impl Into<Option<Vec<object::LocalizedName<'a>>>>,
    ) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `nameLangs` field to an Option value (optional)
    pub fn maybe_name_langs(
        mut self,
        value: Option<Vec<object::LocalizedName<'a>>>,
    ) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<'a, S> ObjectBuilder<'a, S>
where
    S: object_state::State,
    S::Scale: object_state::IsUnset,
{
    /// Set the `scale` field (required)
    pub fn scale(
        mut self,
        value: impl Into<i64>,
    ) -> ObjectBuilder<'a, object_state::SetScale<S>> {
        self._fields.4 = Option::Some(value.into());
        ObjectBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> ObjectBuilder<'a, S>
where
    S: object_state::State,
    S::Scale: object_state::IsSet,
    S::Name: object_state::IsSet,
    S::CreatedAt: object_state::IsSet,
    S::Model: object_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Object<'a> {
        Object {
            created_at: self._fields.0.unwrap(),
            model: self._fields.1.unwrap(),
            name: self._fields.2.unwrap(),
            name_langs: self._fields.3,
            scale: 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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Object<'a> {
        Object {
            created_at: self._fields.0.unwrap(),
            model: self._fields.1.unwrap(),
            name: self._fields.2.unwrap(),
            name_langs: self._fields.3,
            scale: self._fields.4.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}