// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: art.cllctv.feed.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, open_union};
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::art_cllctv::content::markdoc::Markdoc;
use crate::art_cllctv::content::plaintext::Plaintext;
use crate::art_cllctv::embed::Tombstone;
use crate::art_cllctv::embed::external::External;
use crate::art_cllctv::embed::external_video::ExternalVideo;
use crate::art_cllctv::embed::images::Images;
use crate::com_atproto::label::SelfLabels;
use crate::art_cllctv::feed::post;

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct Category<'a> {
    #[serde(borrow)]
    pub group: CowStr<'a>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub labels: Option<Vec<CowStr<'a>>>,
}

/// Record containing a cllctv.ART 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 category: Option<post::Category<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub content: Option<PostContent<'a>>,
    pub created_at: Datetime,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub description: Option<CowStr<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub embed: Option<PostEmbed<'a>>,
    ///Self-label values for this post. Effectively content warnings.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub labels: Option<SelfLabels<'a>>,
    ///Indicates human language of post primary text content.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub langs: Option<Vec<Language>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub og_image: Option<BlobRef<'a>>,
    #[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>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub tombstone: Option<Tombstone<'a>>,
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type")]
#[serde(bound(deserialize = "'de: 'a"))]
pub enum PostContent<'a> {
    #[serde(rename = "art.cllctv.content.plaintext")]
    Plaintext(Box<Plaintext<'a>>),
    #[serde(rename = "art.cllctv.content.markdoc")]
    Markdoc(Box<Markdoc<'a>>),
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type")]
#[serde(bound(deserialize = "'de: 'a"))]
pub enum PostEmbed<'a> {
    #[serde(rename = "art.cllctv.embed.images")]
    Images(Box<Images<'a>>),
    #[serde(rename = "art.cllctv.embed.external")]
    External(Box<External<'a>>),
    #[serde(rename = "art.cllctv.embed.externalVideo")]
    ExternalVideo(Box<ExternalVideo<'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 Category<'a> {
    fn nsid() -> &'static str {
        "art.cllctv.feed.post"
    }
    fn def_name() -> &'static str {
        "category"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_art_cllctv_feed_post()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

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

#[derive(Debug, Serialize, Deserialize)]
pub struct PostRecord;
impl XrpcResp for PostRecord {
    const NSID: &'static str = "art.cllctv.feed.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 = "art.cllctv.feed.post";
    type Record = PostRecord;
}

impl Collection for PostRecord {
    const NSID: &'static str = "art.cllctv.feed.post";
    type Record = PostRecord;
}

impl<'a> LexiconSchema for Post<'a> {
    fn nsid() -> &'static str {
        "art.cllctv.feed.post"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_art_cllctv_feed_post()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.description {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 3000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("description"),
                    max: 3000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.description {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 300usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("description"),
                        max: 300usize,
                        actual: count,
                    });
                }
            }
        }
        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.og_image {
            {
                let size = value.blob().size;
                if size > 5000000usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("og_image"),
                        max: 5000000usize,
                        actual: size,
                    });
                }
            }
        }
        if let Some(ref value) = self.og_image {
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &["image/png"];
                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("og_image"),
                        accepted: vec!["image/png".to_string()],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        if let Some(ref value) = self.title {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 1280usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("title"),
                    max: 1280usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.title {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 128usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("title"),
                        max: 128usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

fn lexicon_doc_art_cllctv_feed_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("art.cllctv.feed.post"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("category"),
                LexUserType::Object(LexObject {
                    required: Some(vec![SmolStr::new_static("group")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("group"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map.insert(
                            SmolStr::new_static("labels"),
                            LexObjectProperty::Array(LexArray {
                                items: LexArrayItem::String(LexString {
                                    ..Default::default()
                                }),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static("Record containing a cllctv.ART post."),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(vec![SmolStr::new_static("createdAt")]),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("category"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("#category"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("content"),
                                LexObjectProperty::Union(LexRefUnion {
                                    refs: vec![
                                        CowStr::new_static("art.cllctv.content.plaintext"),
                                        CowStr::new_static("art.cllctv.content.markdoc")
                                    ],
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("description"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(3000usize),
                                    max_graphemes: Some(300usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("embed"),
                                LexObjectProperty::Union(LexRefUnion {
                                    refs: vec![
                                        CowStr::new_static("art.cllctv.embed.images"),
                                        CowStr::new_static("art.cllctv.embed.external"),
                                        CowStr::new_static("art.cllctv.embed.externalVideo")
                                    ],
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("labels"),
                                LexObjectProperty::Union(LexRefUnion {
                                    description: Some(
                                        CowStr::new_static(
                                            "Self-label values for this post. Effectively content warnings.",
                                        ),
                                    ),
                                    refs: vec![
                                        CowStr::new_static("com.atproto.label.defs#selfLabels")
                                    ],
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("langs"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Indicates human language of post primary text content.",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        format: Some(LexStringFormat::Language),
                                        ..Default::default()
                                    }),
                                    max_length: Some(3usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("ogImage"),
                                LexObjectProperty::Blob(LexBlob { ..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(1280usize),
                                    max_graphemes: Some(128usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("tombstone"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static(
                                        "art.cllctv.embed.defs#tombstone",
                                    ),
                                    ..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 {
        type CreatedAt;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedAt = Unset;
    }
    ///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 CreatedAt = Set<members::created_at>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `created_at` field
        pub struct created_at(());
    }
}

/// Builder for constructing an instance of this type
pub struct PostBuilder<'a, S: post_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<post::Category<'a>>,
        Option<PostContent<'a>>,
        Option<Datetime>,
        Option<CowStr<'a>>,
        Option<PostEmbed<'a>>,
        Option<SelfLabels<'a>>,
        Option<Vec<Language>>,
        Option<BlobRef<'a>>,
        Option<Datetime>,
        Option<CowStr<'a>>,
        Option<Tombstone<'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, None, None, None, None, None, None),
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: post_state::State> PostBuilder<'a, S> {
    /// Set the `category` field (optional)
    pub fn category(mut self, value: impl Into<Option<post::Category<'a>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `category` field to an Option value (optional)
    pub fn maybe_category(mut self, value: Option<post::Category<'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<PostContent<'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<PostContent<'a>>) -> Self {
        self._fields.1 = value;
        self
    }
}

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

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

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

impl<'a, S: post_state::State> PostBuilder<'a, S> {
    /// Set the `labels` field (optional)
    pub fn labels(mut self, value: impl Into<Option<SelfLabels<'a>>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `labels` field to an Option value (optional)
    pub fn maybe_labels(mut self, value: Option<SelfLabels<'a>>) -> Self {
        self._fields.5 = 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.6 = 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.6 = value;
        self
    }
}

impl<'a, S: post_state::State> PostBuilder<'a, S> {
    /// Set the `ogImage` field (optional)
    pub fn og_image(mut self, value: impl Into<Option<BlobRef<'a>>>) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `ogImage` field to an Option value (optional)
    pub fn maybe_og_image(mut self, value: Option<BlobRef<'a>>) -> Self {
        self._fields.7 = 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.8 = 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.8 = 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.9 = 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.9 = value;
        self
    }
}

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

impl<'a, S> PostBuilder<'a, S>
where
    S: post_state::State,
    S::CreatedAt: post_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Post<'a> {
        Post {
            category: self._fields.0,
            content: self._fields.1,
            created_at: self._fields.2.unwrap(),
            description: self._fields.3,
            embed: self._fields.4,
            labels: self._fields.5,
            langs: self._fields.6,
            og_image: self._fields.7,
            published_at: self._fields.8,
            title: self._fields.9,
            tombstone: self._fields.10,
            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 {
            category: self._fields.0,
            content: self._fields.1,
            created_at: self._fields.2.unwrap(),
            description: self._fields.3,
            embed: self._fields.4,
            labels: self._fields.5,
            langs: self._fields.6,
            og_image: self._fields.7,
            published_at: self._fields.8,
            title: self._fields.9,
            tombstone: self._fields.10,
            extra_data: Some(extra_data),
        }
    }
}