// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: app.beaconbits.bookmark.folder
//
// 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};
/// A folder for organizing bookmarks

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "app.beaconbits.bookmark.folder",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Folder<S: BosStr = DefaultStr> {
    ///Hex color code for the folder (e.g., #ff0000)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub color: Option<S>,
    ///Timestamp when the folder was created
    pub created_at: Datetime,
    ///Description of the folder
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<S>,
    ///Lucide icon name
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon: Option<S>,
    ///Display name of the folder
    pub name: S,
    ///Visibility setting for the folder
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visibility: Option<FolderVisibility<S>>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// Visibility setting for the folder

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum FolderVisibility<S: BosStr = DefaultStr> {
    Public,
    Unlisted,
    Hidden,
    Other(S),
}

impl<S: BosStr> FolderVisibility<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Public => "public",
            Self::Unlisted => "unlisted",
            Self::Hidden => "hidden",
            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() {
            "public" => Self::Public,
            "unlisted" => Self::Unlisted,
            "hidden" => Self::Hidden,
            _ => Self::Other(s),
        }
    }
}

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

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

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

impl<S: BosStr> jacquard_common::IntoStatic for FolderVisibility<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = FolderVisibility<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            FolderVisibility::Public => FolderVisibility::Public,
            FolderVisibility::Unlisted => FolderVisibility::Unlisted,
            FolderVisibility::Hidden => FolderVisibility::Hidden,
            FolderVisibility::Other(v) => FolderVisibility::Other(v.into_static()),
        }
    }
}

/// 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 FolderGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Folder<S>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct FolderRecord;
impl XrpcResp for FolderRecord {
    const NSID: &'static str = "app.beaconbits.bookmark.folder";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = FolderGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Folder<S> {
    const NSID: &'static str = "app.beaconbits.bookmark.folder";
    type Record = FolderRecord;
}

impl Collection for FolderRecord {
    const NSID: &'static str = "app.beaconbits.bookmark.folder";
    type Record = FolderRecord;
}

impl<S: BosStr> LexiconSchema for Folder<S> {
    fn nsid() -> &'static str {
        "app.beaconbits.bookmark.folder"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_beaconbits_bookmark_folder()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.color {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 7usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("color"),
                        max: 7usize,
                        actual: count,
                    });
                }
            }
        }
        if let Some(ref value) = self.description {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 280usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("description"),
                        max: 280usize,
                        actual: count,
                    });
                }
            }
        }
        if let Some(ref value) = self.icon {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 64usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("icon"),
                        max: 64usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let value = &self.name;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 64usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("name"),
                        max: 64usize,
                        actual: count,
                    });
                }
            }
        }
        if let Some(ref value) = self.visibility {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 32usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("visibility"),
                        max: 32usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

pub mod folder_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 Name;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedAt = Unset;
        type Name = 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 Name = St::Name;
    }
    ///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 CreatedAt = St::CreatedAt;
        type Name = Set<members::name>;
    }
    /// 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 `name` field
        pub struct name(());
    }
}

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

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

impl<S: BosStr> Folder<S> {
    /// Create a new builder for this type
    pub fn builder() -> FolderBuilder<folder_state::Empty, S> {
        FolderBuilder::builder()
    }
}

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

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

impl<St: folder_state::State, S: BosStr> FolderBuilder<St, S> {
    /// Set the `color` field (optional)
    pub fn color(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `color` field to an Option value (optional)
    pub fn maybe_color(mut self, value: Option<S>) -> Self {
        self._fields.0 = value;
        self
    }
}

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

impl<St: folder_state::State, S: BosStr> FolderBuilder<St, S> {
    /// Set the `description` field (optional)
    pub fn description(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `description` field to an Option value (optional)
    pub fn maybe_description(mut self, value: Option<S>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<St: folder_state::State, S: BosStr> FolderBuilder<St, S> {
    /// Set the `icon` field (optional)
    pub fn icon(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `icon` field to an Option value (optional)
    pub fn maybe_icon(mut self, value: Option<S>) -> Self {
        self._fields.3 = value;
        self
    }
}

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

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

impl<St, S: BosStr> FolderBuilder<St, S>
where
    St: folder_state::State,
    St::CreatedAt: folder_state::IsSet,
    St::Name: folder_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Folder<S> {
        Folder {
            color: self._fields.0,
            created_at: self._fields.1.unwrap(),
            description: self._fields.2,
            icon: self._fields.3,
            name: self._fields.4.unwrap(),
            visibility: 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>>) -> Folder<S> {
        Folder {
            color: self._fields.0,
            created_at: self._fields.1.unwrap(),
            description: self._fields.2,
            icon: self._fields.3,
            name: self._fields.4.unwrap(),
            visibility: self._fields.5,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_app_beaconbits_bookmark_folder() -> 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("app.beaconbits.bookmark.folder"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static("A folder for organizing bookmarks"),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("name"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("color"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Hex color code for the folder (e.g., #ff0000)",
                                        ),
                                    ),
                                    max_graphemes: Some(7usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Timestamp when the folder was created"),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("description"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Description of the folder"),
                                    ),
                                    max_graphemes: Some(280usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("icon"),
                                LexObjectProperty::String(LexString {
                                    description: Some(CowStr::new_static("Lucide icon name")),
                                    max_graphemes: Some(64usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("name"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Display name of the folder"),
                                    ),
                                    max_graphemes: Some(64usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("visibility"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Visibility setting for the folder"),
                                    ),
                                    max_graphemes: Some(32usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}