// @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, 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::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::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};
use crate::tools_smokesignal::blahg::content::post;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Attachment<S: BosStr = DefaultStr> {
    ///Alt text description of the content, for accessibility.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alt: Option<S>,
    pub content: BlobRef<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// A blagh post

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "tools.smokesignal.blahg.content.post",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Post<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attachments: Option<Vec<post::Attachment<S>>>,
    ///The content of the post
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<BlobRef<S>>,
    ///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")]
    pub title: Option<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

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

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

impl<S: BosStr> LexiconSchema for Attachment<S> {
    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<S: BosStr> = PostGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Post<S> {
    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<S: BosStr> LexiconSchema for Post<S> {
    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<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetContent<St> {}
    impl<St: State> State for SetContent<St> {
        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<St: attachment_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (Option<S>, Option<BlobRef<S>>),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

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

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

impl<St, S: BosStr> AttachmentBuilder<St, S>
where
    St: attachment_state::State,
    St::Content: attachment_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Attachment<S> {
        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<SmolStr, Data<S>>,
    ) -> Attachment<S> {
        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<St: post_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Vec<post::Attachment<S>>>,
        Option<BlobRef<S>>,
        Option<Vec<Language>>,
        Option<Datetime>,
        Option<S>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

impl<St: post_state::State, S: BosStr> PostBuilder<St, S> {
    /// Set the `attachments` field (optional)
    pub fn attachments(
        mut self,
        value: impl Into<Option<Vec<post::Attachment<S>>>>,
    ) -> 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<S>>>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St: post_state::State, S: BosStr> PostBuilder<St, S> {
    /// Set the `content` field (optional)
    pub fn content(mut self, value: impl Into<Option<BlobRef<S>>>) -> 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<S>>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<St: post_state::State, S: BosStr> PostBuilder<St, 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<St: post_state::State, S: BosStr> PostBuilder<St, 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<St: post_state::State, S: BosStr> PostBuilder<St, S> {
    /// Set the `title` field (optional)
    pub fn title(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `title` field to an Option value (optional)
    pub fn maybe_title(mut self, value: Option<S>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St, S: BosStr> PostBuilder<St, S>
where
    St: post_state::State,
{
    /// Build the final struct.
    pub fn build(self) -> Post<S> {
        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<SmolStr, Data<S>>) -> Post<S> {
        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),
        }
    }
}