// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: tools.smokesignal.blahg.content.post
//
// 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, 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::tools_smokesignal::blahg::content::post;

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Attachment<'a> {
    ///Alt text description of the content, for accessibility.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub alt: Option<CowStr<'a>>,
    #[serde(borrow)]
    pub content: BlobRef<'a>,
}

/// A blagh post

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Post<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub attachments: Option<Vec<post::Attachment<'a>>>,
    ///The content of the post
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub content: Option<BlobRef<'a>>,
    ///Indicates human language of text content.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub langs: Option<Vec<Language>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub published_at: Option<Datetime>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub title: 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 PostGetRecordOutput<'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: Post<'a>,
}

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

impl<'a> LexiconSchema for Attachment<'a> {
    fn nsid() -> &'static str {
        "tools.smokesignal.blahg.content.post"
    }
    fn def_name() -> &'static str {
        "attachment"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_tools_smokesignal_blahg_content_post()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.content;
            {
                let size = value.blob().size;
                if size > 3000000usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("content"),
                        max: 3000000usize,
                        actual: size,
                    });
                }
            }
        }
        {
            let value = &self.content;
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &["image/*"];
                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("content"),
                        accepted: vec!["image/*".to_string()],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        Ok(())
    }
}

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

#[derive(Debug, Serialize, Deserialize)]
pub struct PostRecord;
impl XrpcResp for PostRecord {
    const NSID: &'static str = "tools.smokesignal.blahg.content.post";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = PostGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Post<'_> {
    const NSID: &'static str = "tools.smokesignal.blahg.content.post";
    type Record = PostRecord;
}

impl Collection for PostRecord {
    const NSID: &'static str = "tools.smokesignal.blahg.content.post";
    type Record = PostRecord;
}

impl<'a> LexiconSchema for Post<'a> {
    fn nsid() -> &'static str {
        "tools.smokesignal.blahg.content.post"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_tools_smokesignal_blahg_content_post()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.content {
            {
                let size = value.blob().size;
                if size > 1000000usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("content"),
                        max: 1000000usize,
                        actual: size,
                    });
                }
            }
        }
        if let Some(ref value) = self.content {
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &["text/plain", "text/html", "text/markdown"];
                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("content"),
                        accepted: vec![
                            "text/plain".to_string(), "text/html".to_string(),
                            "text/markdown".to_string()
                        ],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        if let Some(ref value) = self.langs {
            #[allow(unused_comparisons)]
            if value.len() > 3usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("langs"),
                    max: 3usize,
                    actual: value.len(),
                });
            }
        }
        if let Some(ref value) = self.title {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 2000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("title"),
                    max: 2000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.title {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 200usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("title"),
                        max: 200usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

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

/// Builder for constructing an instance of this type
pub struct AttachmentBuilder<'a, S: attachment_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (Option<CowStr<'a>>, Option<BlobRef<'a>>),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Attachment<'a> {
    /// Create a new builder for this type
    pub fn new() -> AttachmentBuilder<'a, attachment_state::Empty> {
        AttachmentBuilder::new()
    }
}

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

impl<'a, S: attachment_state::State> AttachmentBuilder<'a, S> {
    /// Set the `alt` field (optional)
    pub fn alt(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `alt` field to an Option value (optional)
    pub fn maybe_alt(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.0 = value;
        self
    }
}

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

impl<'a, S> AttachmentBuilder<'a, S>
where
    S: attachment_state::State,
    S::Content: attachment_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Attachment<'a> {
        Attachment {
            alt: self._fields.0,
            content: 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>,
        >,
    ) -> Attachment<'a> {
        Attachment {
            alt: self._fields.0,
            content: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_tools_smokesignal_blahg_content_post() -> 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("tools.smokesignal.blahg.content.post"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("attachment"),
                LexUserType::Object(LexObject {
                    required: Some(vec![SmolStr::new_static("content")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("alt"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "Alt text description of the content, for accessibility.",
                                    ),
                                ),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("content"),
                            LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(CowStr::new_static("A blagh post")),
                    key: Some(CowStr::new_static("any")),
                    record: LexRecordRecord::Object(LexObject {
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("attachments"),
                                LexObjectProperty::Array(LexArray {
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#attachment"),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("content"),
                                LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                            );
                            map.insert(
                                SmolStr::new_static("langs"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Indicates human language of text content.",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        format: Some(LexStringFormat::Language),
                                        ..Default::default()
                                    }),
                                    max_length: Some(3usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("publishedAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("title"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(2000usize),
                                    max_graphemes: Some(200usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod post_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 {}
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {}
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {}
}

/// Builder for constructing an instance of this type
pub struct PostBuilder<'a, S: post_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Vec<post::Attachment<'a>>>,
        Option<BlobRef<'a>>,
        Option<Vec<Language>>,
        Option<Datetime>,
        Option<CowStr<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Post<'a> {
    /// Create a new builder for this type
    pub fn new() -> PostBuilder<'a, post_state::Empty> {
        PostBuilder::new()
    }
}

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

impl<'a, S: post_state::State> PostBuilder<'a, S> {
    /// Set the `attachments` field (optional)
    pub fn attachments(
        mut self,
        value: impl Into<Option<Vec<post::Attachment<'a>>>>,
    ) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `attachments` field to an Option value (optional)
    pub fn maybe_attachments(
        mut self,
        value: Option<Vec<post::Attachment<'a>>>,
    ) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<'a, S: post_state::State> PostBuilder<'a, S> {
    /// Set the `content` field (optional)
    pub fn content(mut self, value: impl Into<Option<BlobRef<'a>>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `content` field to an Option value (optional)
    pub fn maybe_content(mut self, value: Option<BlobRef<'a>>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<'a, S: post_state::State> PostBuilder<'a, S> {
    /// Set the `langs` field (optional)
    pub fn langs(mut self, value: impl Into<Option<Vec<Language>>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `langs` field to an Option value (optional)
    pub fn maybe_langs(mut self, value: Option<Vec<Language>>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<'a, S: post_state::State> PostBuilder<'a, S> {
    /// Set the `publishedAt` field (optional)
    pub fn published_at(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `publishedAt` field to an Option value (optional)
    pub fn maybe_published_at(mut self, value: Option<Datetime>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<'a, S: post_state::State> PostBuilder<'a, S> {
    /// Set the `title` field (optional)
    pub fn title(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `title` field to an Option value (optional)
    pub fn maybe_title(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<'a, S> PostBuilder<'a, S>
where
    S: post_state::State,
{
    /// Build the final struct
    pub fn build(self) -> Post<'a> {
        Post {
            attachments: self._fields.0,
            content: self._fields.1,
            langs: self._fields.2,
            published_at: self._fields.3,
            title: self._fields.4,
            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>,
        >,
    ) -> Post<'a> {
        Post {
            attachments: self._fields.0,
            content: self._fields.1,
            langs: self._fields.2,
            published_at: self._fields.3,
            title: self._fields.4,
            extra_data: Some(extra_data),
        }
    }
}