// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: app.greengale.document
//
// 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, 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::app_greengale::blog::BlobMetadata;
use crate::app_greengale::blog::Ogp;
use crate::app_greengale::blog::Theme;
/// Reference to external content via AT-URI. Used in site.standard.document content union.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct ContentRef<'a> {
    ///AT-URI pointing to the full document content
    #[serde(borrow)]
    pub uri: AtUri<'a>,
}

/// A markdown document with extended theme and LaTeX support.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Document<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub blobs: Option<Vec<BlobMetadata<'a>>>,
    ///Markdown content of the document
    #[serde(borrow)]
    pub content: CowStr<'a>,
    ///Legacy field for LaTeX math rendering. LaTeX is now always enabled for GreenGale posts; this field is kept for backward compatibility.  Defaults to `false`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default = "_default_document_latex")]
    pub latex: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub ogp: Option<Ogp<'a>>,
    ///Document path relative to the publication URL (e.g., /handle/rkey)
    #[serde(borrow)]
    pub path: CowStr<'a>,
    ///Publication timestamp
    pub published_at: Datetime,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub subtitle: Option<CowStr<'a>>,
    ///Optional array of strings to tag/categorize the document. Avoid prepending with hashtags.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub tags: Option<Vec<CowStr<'a>>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub theme: Option<Theme<'a>>,
    ///Document title
    #[serde(borrow)]
    pub title: CowStr<'a>,
    ///Base publication URL (e.g., https://greengale.app)
    #[serde(borrow)]
    pub url: UriValue<'a>,
    ///Controls who can view this document  Defaults to `"public"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default = "_default_document_visibility")]
    #[serde(borrow)]
    pub visibility: 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 DocumentGetRecordOutput<'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: Document<'a>,
}

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

impl<'a> LexiconSchema for ContentRef<'a> {
    fn nsid() -> &'static str {
        "app.greengale.document"
    }
    fn def_name() -> &'static str {
        "contentRef"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_greengale_document()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

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

#[derive(Debug, Serialize, Deserialize)]
pub struct DocumentRecord;
impl XrpcResp for DocumentRecord {
    const NSID: &'static str = "app.greengale.document";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = DocumentGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Document<'_> {
    const NSID: &'static str = "app.greengale.document";
    type Record = DocumentRecord;
}

impl Collection for DocumentRecord {
    const NSID: &'static str = "app.greengale.document";
    type Record = DocumentRecord;
}

impl<'a> LexiconSchema for Document<'a> {
    fn nsid() -> &'static str {
        "app.greengale.document"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_greengale_document()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.content;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 100000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("content"),
                    max: 100000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.path;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 500usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("path"),
                    max: 500usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.subtitle {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 1000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("subtitle"),
                    max: 1000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.tags {
            #[allow(unused_comparisons)]
            if value.len() > 100usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("tags"),
                    max: 100usize,
                    actual: value.len(),
                });
            }
        }
        {
            let value = &self.title;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 1000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("title"),
                    max: 1000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.url;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 2048usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("url"),
                    max: 2048usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.visibility {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 16usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("visibility"),
                    max: 16usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

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

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

impl<'a> ContentRef<'a> {
    /// Create a new builder for this type
    pub fn new() -> ContentRefBuilder<'a, content_ref_state::Empty> {
        ContentRefBuilder::new()
    }
}

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

impl<'a, S> ContentRefBuilder<'a, S>
where
    S: content_ref_state::State,
    S::Uri: content_ref_state::IsUnset,
{
    /// Set the `uri` field (required)
    pub fn uri(
        mut self,
        value: impl Into<AtUri<'a>>,
    ) -> ContentRefBuilder<'a, content_ref_state::SetUri<S>> {
        self._fields.0 = Option::Some(value.into());
        ContentRefBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> ContentRefBuilder<'a, S>
where
    S: content_ref_state::State,
    S::Uri: content_ref_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> ContentRef<'a> {
        ContentRef {
            uri: self._fields.0.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>,
        >,
    ) -> ContentRef<'a> {
        ContentRef {
            uri: self._fields.0.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_app_greengale_document() -> LexiconDoc<'static> {
    #[allow(unused_imports)]
    use jacquard_common::{CowStr, deps::smol_str::SmolStr, types::blob::MimeType};
    use jacquard_lexicon::lexicon::*;
    use alloc::collections::BTreeMap;
    LexiconDoc {
        lexicon: Lexicon::Lexicon1,
        id: CowStr::new_static("app.greengale.document"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("contentRef"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "Reference to external content via AT-URI. Used in site.standard.document content union.",
                        ),
                    ),
                    required: Some(vec![SmolStr::new_static("uri")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("uri"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "AT-URI pointing to the full document content",
                                    ),
                                ),
                                format: Some(LexStringFormat::AtUri),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A markdown document with extended theme and LaTeX support.",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("content"), SmolStr::new_static("url"),
                                SmolStr::new_static("path"), SmolStr::new_static("title"),
                                SmolStr::new_static("publishedAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("blobs"),
                                LexObjectProperty::Array(LexArray {
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static(
                                            "app.greengale.blog.defs#blobMetadata",
                                        ),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("content"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Markdown content of the document"),
                                    ),
                                    max_length: Some(100000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("latex"),
                                LexObjectProperty::Boolean(LexBoolean {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("ogp"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("app.greengale.blog.defs#ogp"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("path"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Document path relative to the publication URL (e.g., /handle/rkey)",
                                        ),
                                    ),
                                    max_length: Some(500usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("publishedAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Publication timestamp"),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("subtitle"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(1000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("tags"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Optional array of strings to tag/categorize the document. Avoid prepending with hashtags.",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        max_length: Some(100usize),
                                        max_graphemes: Some(50usize),
                                        ..Default::default()
                                    }),
                                    max_length: Some(100usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("theme"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("app.greengale.blog.defs#theme"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("title"),
                                LexObjectProperty::String(LexString {
                                    description: Some(CowStr::new_static("Document title")),
                                    max_length: Some(1000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("url"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Base publication URL (e.g., https://greengale.app)",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Uri),
                                    max_length: Some(2048usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("visibility"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Controls who can view this document"),
                                    ),
                                    max_length: Some(16usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

fn _default_document_latex() -> Option<bool> {
    Some(false)
}

fn _default_document_visibility() -> Option<CowStr<'static>> {
    Some(CowStr::from("public"))
}

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

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

impl<'a> Document<'a> {
    /// Create a new builder for this type
    pub fn new() -> DocumentBuilder<'a, document_state::Empty> {
        DocumentBuilder::new()
    }
}

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

impl<'a, S: document_state::State> DocumentBuilder<'a, S> {
    /// Set the `blobs` field (optional)
    pub fn blobs(mut self, value: impl Into<Option<Vec<BlobMetadata<'a>>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `blobs` field to an Option value (optional)
    pub fn maybe_blobs(mut self, value: Option<Vec<BlobMetadata<'a>>>) -> Self {
        self._fields.0 = value;
        self
    }
}

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

impl<'a, S: document_state::State> DocumentBuilder<'a, S> {
    /// Set the `latex` field (optional)
    pub fn latex(mut self, value: impl Into<Option<bool>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `latex` field to an Option value (optional)
    pub fn maybe_latex(mut self, value: Option<bool>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<'a, S: document_state::State> DocumentBuilder<'a, S> {
    /// Set the `ogp` field (optional)
    pub fn ogp(mut self, value: impl Into<Option<Ogp<'a>>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `ogp` field to an Option value (optional)
    pub fn maybe_ogp(mut self, value: Option<Ogp<'a>>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<'a, S> DocumentBuilder<'a, S>
where
    S: document_state::State,
    S::Path: document_state::IsUnset,
{
    /// Set the `path` field (required)
    pub fn path(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> DocumentBuilder<'a, document_state::SetPath<S>> {
        self._fields.4 = Option::Some(value.into());
        DocumentBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> DocumentBuilder<'a, S>
where
    S: document_state::State,
    S::PublishedAt: document_state::IsUnset,
{
    /// Set the `publishedAt` field (required)
    pub fn published_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> DocumentBuilder<'a, document_state::SetPublishedAt<S>> {
        self._fields.5 = Option::Some(value.into());
        DocumentBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: document_state::State> DocumentBuilder<'a, S> {
    /// Set the `subtitle` field (optional)
    pub fn subtitle(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.6 = value.into();
        self
    }
    /// Set the `subtitle` field to an Option value (optional)
    pub fn maybe_subtitle(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.6 = value;
        self
    }
}

impl<'a, S: document_state::State> DocumentBuilder<'a, S> {
    /// Set the `tags` field (optional)
    pub fn tags(mut self, value: impl Into<Option<Vec<CowStr<'a>>>>) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `tags` field to an Option value (optional)
    pub fn maybe_tags(mut self, value: Option<Vec<CowStr<'a>>>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<'a, S: document_state::State> DocumentBuilder<'a, S> {
    /// Set the `theme` field (optional)
    pub fn theme(mut self, value: impl Into<Option<Theme<'a>>>) -> Self {
        self._fields.8 = value.into();
        self
    }
    /// Set the `theme` field to an Option value (optional)
    pub fn maybe_theme(mut self, value: Option<Theme<'a>>) -> Self {
        self._fields.8 = value;
        self
    }
}

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

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

impl<'a, S: document_state::State> DocumentBuilder<'a, S> {
    /// Set the `visibility` field (optional)
    pub fn visibility(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.11 = value.into();
        self
    }
    /// Set the `visibility` field to an Option value (optional)
    pub fn maybe_visibility(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.11 = value;
        self
    }
}

impl<'a, S> DocumentBuilder<'a, S>
where
    S: document_state::State,
    S::Url: document_state::IsSet,
    S::Title: document_state::IsSet,
    S::Path: document_state::IsSet,
    S::Content: document_state::IsSet,
    S::PublishedAt: document_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Document<'a> {
        Document {
            blobs: self._fields.0,
            content: self._fields.1.unwrap(),
            latex: self._fields.2.or_else(|| Some(false)),
            ogp: self._fields.3,
            path: self._fields.4.unwrap(),
            published_at: self._fields.5.unwrap(),
            subtitle: self._fields.6,
            tags: self._fields.7,
            theme: self._fields.8,
            title: self._fields.9.unwrap(),
            url: self._fields.10.unwrap(),
            visibility: self._fields.11.or_else(|| Some(CowStr::from("public"))),
            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>,
        >,
    ) -> Document<'a> {
        Document {
            blobs: self._fields.0,
            content: self._fields.1.unwrap(),
            latex: self._fields.2.or_else(|| Some(false)),
            ogp: self._fields.3,
            path: self._fields.4.unwrap(),
            published_at: self._fields.5.unwrap(),
            subtitle: self._fields.6,
            tags: self._fields.7,
            theme: self._fields.8,
            title: self._fields.9.unwrap(),
            url: self._fields.10.unwrap(),
            visibility: self._fields.11.or_else(|| Some(CowStr::from("public"))),
            extra_data: Some(extra_data),
        }
    }
}