// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: social.clippr.feed.clip
//
// 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::{AtUri, Cid, Datetime, Language, UriValue};
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::com_atproto::repo::strong_ref::StrongRef;
/// Record containing a bookmarked item, or 'clip'.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Clip<'a> {
    ///Client-declared timestamp when the bookmark is created
    pub created_at: Datetime,
    ///A description of the bookmark's content. This should be ripped from the URL metadata and be static for all records using the URL.
    #[serde(borrow)]
    pub description: CowStr<'a>,
    ///Indicates human language of the given URL
    #[serde(skip_serializing_if = "Option::is_none")]
    pub languages: Option<Vec<Language>>,
    ///User-written notes for the bookmark. Public and personal.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub notes: Option<CowStr<'a>>,
    ///An array of tags. A format of solely alphanumeric characters and dashes should be used.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub tags: Option<Vec<StrongRef<'a>>>,
    ///The title of the bookmark. If left empty, reuse the URL.
    #[serde(borrow)]
    pub title: CowStr<'a>,
    ///Whether the bookmark can be used for feed indexing and aggregation  Defaults to `false`.
    #[serde(default = "_default_clip_unlisted")]
    pub unlisted: bool,
    ///Whether the bookmark has been read by the user  Defaults to `true`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default = "_default_clip_unread")]
    pub unread: Option<bool>,
    ///The URL of the bookmark. Cannot be left empty or be modified after creation.
    #[serde(borrow)]
    pub url: UriValue<'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 ClipGetRecordOutput<'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: Clip<'a>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct ClipRecord;
impl XrpcResp for ClipRecord {
    const NSID: &'static str = "social.clippr.feed.clip";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = ClipGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Clip<'_> {
    const NSID: &'static str = "social.clippr.feed.clip";
    type Record = ClipRecord;
}

impl Collection for ClipRecord {
    const NSID: &'static str = "social.clippr.feed.clip";
    type Record = ClipRecord;
}

impl<'a> LexiconSchema for Clip<'a> {
    fn nsid() -> &'static str {
        "social.clippr.feed.clip"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_social_clippr_feed_clip()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.description;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 40960usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("description"),
                    max: 40960usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.description;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 4096usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("description"),
                        max: 4096usize,
                        actual: count,
                    });
                }
            }
        }
        if let Some(ref value) = self.languages {
            #[allow(unused_comparisons)]
            if value.len() > 5usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("languages"),
                    max: 5usize,
                    actual: value.len(),
                });
            }
        }
        if let Some(ref value) = self.notes {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 100000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("notes"),
                    max: 100000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.notes {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 10000usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("notes"),
                        max: 10000usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let value = &self.title;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 20480usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("title"),
                    max: 20480usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.title;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 2048usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("title"),
                        max: 2048usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let value = &self.url;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 20000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("url"),
                    max: 20000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.url;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 2000usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("url"),
                        max: 2000usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

fn _default_clip_unlisted() -> bool {
    false
}

fn _default_clip_unread() -> Option<bool> {
    Some(true)
}

pub mod clip_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 Unlisted;
        type Url;
        type CreatedAt;
        type Description;
        type Title;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Unlisted = Unset;
        type Url = Unset;
        type CreatedAt = Unset;
        type Description = Unset;
        type Title = Unset;
    }
    ///State transition - sets the `unlisted` field to Set
    pub struct SetUnlisted<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetUnlisted<S> {}
    impl<S: State> State for SetUnlisted<S> {
        type Unlisted = Set<members::unlisted>;
        type Url = S::Url;
        type CreatedAt = S::CreatedAt;
        type Description = S::Description;
        type Title = S::Title;
    }
    ///State transition - sets the `url` field to Set
    pub struct SetUrl<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetUrl<S> {}
    impl<S: State> State for SetUrl<S> {
        type Unlisted = S::Unlisted;
        type Url = Set<members::url>;
        type CreatedAt = S::CreatedAt;
        type Description = S::Description;
        type Title = S::Title;
    }
    ///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 Unlisted = S::Unlisted;
        type Url = S::Url;
        type CreatedAt = Set<members::created_at>;
        type Description = S::Description;
        type Title = S::Title;
    }
    ///State transition - sets the `description` field to Set
    pub struct SetDescription<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetDescription<S> {}
    impl<S: State> State for SetDescription<S> {
        type Unlisted = S::Unlisted;
        type Url = S::Url;
        type CreatedAt = S::CreatedAt;
        type Description = Set<members::description>;
        type Title = S::Title;
    }
    ///State transition - sets the `title` field to Set
    pub struct SetTitle<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetTitle<S> {}
    impl<S: State> State for SetTitle<S> {
        type Unlisted = S::Unlisted;
        type Url = S::Url;
        type CreatedAt = S::CreatedAt;
        type Description = S::Description;
        type Title = Set<members::title>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `unlisted` field
        pub struct unlisted(());
        ///Marker type for the `url` field
        pub struct url(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `description` field
        pub struct description(());
        ///Marker type for the `title` field
        pub struct title(());
    }
}

/// Builder for constructing an instance of this type
pub struct ClipBuilder<'a, S: clip_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Datetime>,
        Option<CowStr<'a>>,
        Option<Vec<Language>>,
        Option<CowStr<'a>>,
        Option<Vec<StrongRef<'a>>>,
        Option<CowStr<'a>>,
        Option<bool>,
        Option<bool>,
        Option<UriValue<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Clip<'a> {
    /// Create a new builder for this type
    pub fn new() -> ClipBuilder<'a, clip_state::Empty> {
        ClipBuilder::new()
    }
}

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

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

impl<'a, S> ClipBuilder<'a, S>
where
    S: clip_state::State,
    S::Description: clip_state::IsUnset,
{
    /// Set the `description` field (required)
    pub fn description(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> ClipBuilder<'a, clip_state::SetDescription<S>> {
        self._fields.1 = Option::Some(value.into());
        ClipBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: clip_state::State> ClipBuilder<'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: clip_state::State> ClipBuilder<'a, S> {
    /// Set the `notes` field (optional)
    pub fn notes(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `notes` field to an Option value (optional)
    pub fn maybe_notes(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.3 = value;
        self
    }
}

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

impl<'a, S> ClipBuilder<'a, S>
where
    S: clip_state::State,
    S::Title: clip_state::IsUnset,
{
    /// Set the `title` field (required)
    pub fn title(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> ClipBuilder<'a, clip_state::SetTitle<S>> {
        self._fields.5 = Option::Some(value.into());
        ClipBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> ClipBuilder<'a, S>
where
    S: clip_state::State,
    S::Unlisted: clip_state::IsUnset,
{
    /// Set the `unlisted` field (required)
    pub fn unlisted(
        mut self,
        value: impl Into<bool>,
    ) -> ClipBuilder<'a, clip_state::SetUnlisted<S>> {
        self._fields.6 = Option::Some(value.into());
        ClipBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: clip_state::State> ClipBuilder<'a, S> {
    /// Set the `unread` field (optional)
    pub fn unread(mut self, value: impl Into<Option<bool>>) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `unread` field to an Option value (optional)
    pub fn maybe_unread(mut self, value: Option<bool>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<'a, S> ClipBuilder<'a, S>
where
    S: clip_state::State,
    S::Url: clip_state::IsUnset,
{
    /// Set the `url` field (required)
    pub fn url(
        mut self,
        value: impl Into<UriValue<'a>>,
    ) -> ClipBuilder<'a, clip_state::SetUrl<S>> {
        self._fields.8 = Option::Some(value.into());
        ClipBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> ClipBuilder<'a, S>
where
    S: clip_state::State,
    S::Unlisted: clip_state::IsSet,
    S::Url: clip_state::IsSet,
    S::CreatedAt: clip_state::IsSet,
    S::Description: clip_state::IsSet,
    S::Title: clip_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Clip<'a> {
        Clip {
            created_at: self._fields.0.unwrap(),
            description: self._fields.1.unwrap(),
            languages: self._fields.2,
            notes: self._fields.3,
            tags: self._fields.4,
            title: self._fields.5.unwrap(),
            unlisted: self._fields.6.unwrap(),
            unread: self._fields.7.or_else(|| Some(true)),
            url: self._fields.8.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>,
        >,
    ) -> Clip<'a> {
        Clip {
            created_at: self._fields.0.unwrap(),
            description: self._fields.1.unwrap(),
            languages: self._fields.2,
            notes: self._fields.3,
            tags: self._fields.4,
            title: self._fields.5.unwrap(),
            unlisted: self._fields.6.unwrap(),
            unread: self._fields.7.or_else(|| Some(true)),
            url: self._fields.8.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_social_clippr_feed_clip() -> 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.clippr.feed.clip"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "Record containing a bookmarked item, or 'clip'.",
                        ),
                    ),
                    key: Some(CowStr::new_static("any")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("url"), SmolStr::new_static("title"),
                                SmolStr::new_static("description"),
                                SmolStr::new_static("unlisted"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Client-declared timestamp when the bookmark is created",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("description"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "A description of the bookmark's content. This should be ripped from the URL metadata and be static for all records using the URL.",
                                        ),
                                    ),
                                    max_length: Some(40960usize),
                                    max_graphemes: Some(4096usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("languages"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Indicates human language of the given URL",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        format: Some(LexStringFormat::Language),
                                        ..Default::default()
                                    }),
                                    max_length: Some(5usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("notes"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "User-written notes for the bookmark. Public and personal.",
                                        ),
                                    ),
                                    max_length: Some(100000usize),
                                    max_graphemes: Some(10000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("tags"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "An array of tags. A format of solely alphanumeric characters and dashes should be used.",
                                        ),
                                    ),
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("com.atproto.repo.strongRef"),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("title"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The title of the bookmark. If left empty, reuse the URL.",
                                        ),
                                    ),
                                    max_length: Some(20480usize),
                                    max_graphemes: Some(2048usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("unlisted"),
                                LexObjectProperty::Boolean(LexBoolean {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("unread"),
                                LexObjectProperty::Boolean(LexBoolean {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("url"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The URL of the bookmark. Cannot be left empty or be modified after creation.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Uri),
                                    max_length: Some(20000usize),
                                    max_graphemes: Some(2000usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}