// @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, 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::collection::{Collection, RecordError};
use jacquard_common::types::string::{AtUri, Cid, Datetime, UriValue};
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::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.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct ContentRef<S: BosStr = DefaultStr> {
    ///AT-URI pointing to the full document content
    pub uri: AtUri<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

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

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "app.greengale.document",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Document<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blobs: Option<Vec<BlobMetadata<S>>>,
    ///Markdown content of the document
    pub content: S,
    ///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")]
    pub ogp: Option<Ogp<S>>,
    ///Document path relative to the publication URL (e.g., /handle/rkey)
    pub path: S,
    ///Publication timestamp
    pub published_at: Datetime,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subtitle: Option<S>,
    ///Optional array of strings to tag/categorize the document. Avoid prepending with hashtags.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<S>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub theme: Option<Theme<S>>,
    ///Document title
    pub title: S,
    ///Base publication URL (e.g., https://greengale.app)
    pub url: UriValue<S>,
    ///Controls who can view this document  Defaults to `"public"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default = "_default_document_visibility")]
    pub visibility: 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 DocumentGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Document<S>,
}

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

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

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

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

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

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

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

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

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

impl<St, S: BosStr> ContentRefBuilder<St, S>
where
    St: content_ref_state::State,
    St::Uri: content_ref_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> ContentRef<S> {
        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<SmolStr, Data<S>>,
    ) -> ContentRef<S> {
        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<S: FromStaticStr>() -> ::core::option::Option<S> {
    Some(S::from_static("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 Content;
        type Path;
        type PublishedAt;
        type Title;
        type Url;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Content = Unset;
        type Path = Unset;
        type PublishedAt = Unset;
        type Title = Unset;
        type Url = 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>;
        type Path = St::Path;
        type PublishedAt = St::PublishedAt;
        type Title = St::Title;
        type Url = St::Url;
    }
    ///State transition - sets the `path` field to Set
    pub struct SetPath<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetPath<St> {}
    impl<St: State> State for SetPath<St> {
        type Content = St::Content;
        type Path = Set<members::path>;
        type PublishedAt = St::PublishedAt;
        type Title = St::Title;
        type Url = St::Url;
    }
    ///State transition - sets the `published_at` field to Set
    pub struct SetPublishedAt<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetPublishedAt<St> {}
    impl<St: State> State for SetPublishedAt<St> {
        type Content = St::Content;
        type Path = St::Path;
        type PublishedAt = Set<members::published_at>;
        type Title = St::Title;
        type Url = St::Url;
    }
    ///State transition - sets the `title` field to Set
    pub struct SetTitle<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetTitle<St> {}
    impl<St: State> State for SetTitle<St> {
        type Content = St::Content;
        type Path = St::Path;
        type PublishedAt = St::PublishedAt;
        type Title = Set<members::title>;
        type Url = St::Url;
    }
    ///State transition - sets the `url` field to Set
    pub struct SetUrl<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetUrl<St> {}
    impl<St: State> State for SetUrl<St> {
        type Content = St::Content;
        type Path = St::Path;
        type PublishedAt = St::PublishedAt;
        type Title = St::Title;
        type Url = Set<members::url>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `content` field
        pub struct content(());
        ///Marker type for the `path` field
        pub struct path(());
        ///Marker type for the `published_at` field
        pub struct published_at(());
        ///Marker type for the `title` field
        pub struct title(());
        ///Marker type for the `url` field
        pub struct url(());
    }
}

/// Builder for constructing an instance of this type.
pub struct DocumentBuilder<St: document_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Vec<BlobMetadata<S>>>,
        Option<S>,
        Option<bool>,
        Option<Ogp<S>>,
        Option<S>,
        Option<Datetime>,
        Option<S>,
        Option<Vec<S>>,
        Option<Theme<S>>,
        Option<S>,
        Option<UriValue<S>>,
        Option<S>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

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

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

impl<St: document_state::State, S: BosStr> DocumentBuilder<St, 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<St: document_state::State, S: BosStr> DocumentBuilder<St, S> {
    /// Set the `ogp` field (optional)
    pub fn ogp(mut self, value: impl Into<Option<Ogp<S>>>) -> 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<S>>) -> Self {
        self._fields.3 = value;
        self
    }
}

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

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

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

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

impl<St: document_state::State, S: BosStr> DocumentBuilder<St, S> {
    /// Set the `theme` field (optional)
    pub fn theme(mut self, value: impl Into<Option<Theme<S>>>) -> 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<S>>) -> Self {
        self._fields.8 = value;
        self
    }
}

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

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

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

impl<St, S: BosStr> DocumentBuilder<St, S>
where
    St: document_state::State,
    St::Content: document_state::IsSet,
    St::Path: document_state::IsSet,
    St::PublishedAt: document_state::IsSet,
    St::Title: document_state::IsSet,
    St::Url: document_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Document<S> {
        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(S::from_static("public"))),
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(self, extra_data: BTreeMap<SmolStr, Data<S>>) -> Document<S> {
        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(S::from_static("public"))),
            extra_data: Some(extra_data),
        }
    }
}