// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: app.chronosky.schedule.createPost
//
// 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::string::{Datetime, Language};
use jacquard_common::types::value::Data;
use jacquard_derive::{IntoStatic, 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::app_bsky::embed::external::ExternalRecord;
use crate::app_bsky::embed::images::Images;
use crate::app_bsky::embed::record::Record;
use crate::app_bsky::embed::record_with_media::RecordWithMedia;
use crate::app_bsky::embed::video::Video;
use crate::app_bsky::feed::threadgate::FollowerRule;
use crate::app_bsky::feed::threadgate::FollowingRule;
use crate::app_bsky::feed::threadgate::ListRule;
use crate::app_bsky::feed::threadgate::MentionRule;
use crate::app_bsky::richtext::facet::Facet;
use crate::com_atproto::label::SelfLabels;
use crate::app_chronosky::schedule::create_post;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct CreatePost<S: BosStr = DefaultStr> {
    ///Whether to disable quote posts
    #[serde(skip_serializing_if = "Option::is_none")]
    pub disable_quote_posts: Option<bool>,
    ///Chronosky-internal scheduled post ID of the parent post (for scheduling threads or replies). Not an AT Protocol URI or Record Key.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_post_id: Option<S>,
    ///Array of posts to schedule (1 element = single post, multiple = thread)
    pub posts: Vec<create_post::ThreadPostInput<S>>,
    ///Scheduled publish time
    pub scheduled_at: Datetime,
    ///Thread gate rules to control who can reply
    #[serde(skip_serializing_if = "Option::is_none")]
    pub threadgate_rules: Option<Vec<CreatePostThreadgateRulesItem<S>>>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub enum CreatePostThreadgateRulesItem<S: BosStr = DefaultStr> {
    #[serde(rename = "app.bsky.feed.threadgate#mentionRule")]
    ThreadgateMentionRule(Box<MentionRule<S>>),
    #[serde(rename = "app.bsky.feed.threadgate#followerRule")]
    ThreadgateFollowerRule(Box<FollowerRule<S>>),
    #[serde(rename = "app.bsky.feed.threadgate#followingRule")]
    ThreadgateFollowingRule(Box<FollowingRule<S>>),
    #[serde(rename = "app.bsky.feed.threadgate#listRule")]
    ThreadgateListRule(Box<ListRule<S>>),
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct CreatePostOutput<S: BosStr = DefaultStr> {
    ///Chronosky schedule ID (parent post ID for threads)
    pub id: S,
    ///Number of posts created (1 for single post, N for thread)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub post_count: Option<i64>,
    pub scheduled_at: Datetime,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// Individual post input for thread scheduling.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct ThreadPostInput<S: BosStr = DefaultStr> {
    ///Post creation timestamp (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<Datetime>,
    ///Embedded content (images, external links, records).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub embed: Option<ThreadPostInputEmbed<S>>,
    ///Rich text facets (mentions, links, tags)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub facets: Option<Vec<Facet<S>>>,
    ///Self-applied content labels for content warnings (AT Protocol standard).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub labels: Option<SelfLabels<S>>,
    ///Language codes (ISO 639-1)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub langs: Option<Vec<Language>>,
    ///Post text content
    pub text: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub enum ThreadPostInputEmbed<S: BosStr = DefaultStr> {
    #[serde(rename = "app.bsky.embed.images")]
    Images(Box<Images<S>>),
    #[serde(rename = "app.bsky.embed.external")]
    External(Box<ExternalRecord<S>>),
    #[serde(rename = "app.bsky.embed.record")]
    Record(Box<Record<S>>),
    #[serde(rename = "app.bsky.embed.video")]
    Video(Box<Video<S>>),
    #[serde(rename = "app.bsky.embed.recordWithMedia")]
    RecordWithMedia(Box<RecordWithMedia<S>>),
}

/** Response marker for the `app.chronosky.schedule.createPost` procedure.

Implements `jacquard_common::xrpc::XrpcResp`; successful bodies decode as `Self::Output<S>`, which is `CreatePostOutput<S>` for this endpoint.*/
pub struct CreatePostResponse;
impl jacquard_common::xrpc::XrpcResp for CreatePostResponse {
    const NSID: &'static str = "app.chronosky.schedule.createPost";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = CreatePostOutput<S>;
    type Err = jacquard_common::xrpc::GenericError;
}

impl<S: BosStr> jacquard_common::xrpc::XrpcRequest for CreatePost<S> {
    const NSID: &'static str = "app.chronosky.schedule.createPost";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Procedure(
        "application/json",
    );
    type Response = CreatePostResponse;
}

/** Endpoint marker for the `app.chronosky.schedule.createPost` procedure.

Path: `/xrpc/app.chronosky.schedule.createPost`. The request payload type is `CreatePost<S>`; send that request with `jacquard::Client` or use this marker through lower-level `XrpcEndpoint` APIs.*/
pub struct CreatePostRequest;
impl jacquard_common::xrpc::XrpcEndpoint for CreatePostRequest {
    const PATH: &'static str = "/xrpc/app.chronosky.schedule.createPost";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Procedure(
        "application/json",
    );
    type Request<S: BosStr> = CreatePost<S>;
    type Response = CreatePostResponse;
}

impl<S: BosStr> LexiconSchema for ThreadPostInput<S> {
    fn nsid() -> &'static str {
        "app.chronosky.schedule.createPost"
    }
    fn def_name() -> &'static str {
        "threadPostInput"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_chronosky_schedule_createPost()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.facets {
            #[allow(unused_comparisons)]
            if value.len() > 50usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("facets"),
                    max: 50usize,
                    actual: value.len(),
                });
            }
        }
        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(),
                });
            }
        }
        {
            let value = &self.text;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 3000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("text"),
                    max: 3000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.text;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 300usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("text"),
                        max: 300usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

pub mod create_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 Posts;
        type ScheduledAt;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Posts = Unset;
        type ScheduledAt = Unset;
    }
    ///State transition - sets the `posts` field to Set
    pub struct SetPosts<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetPosts<St> {}
    impl<St: State> State for SetPosts<St> {
        type Posts = Set<members::posts>;
        type ScheduledAt = St::ScheduledAt;
    }
    ///State transition - sets the `scheduled_at` field to Set
    pub struct SetScheduledAt<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetScheduledAt<St> {}
    impl<St: State> State for SetScheduledAt<St> {
        type Posts = St::Posts;
        type ScheduledAt = Set<members::scheduled_at>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `posts` field
        pub struct posts(());
        ///Marker type for the `scheduled_at` field
        pub struct scheduled_at(());
    }
}

/// Builder for constructing an instance of this type.
pub struct CreatePostBuilder<St: create_post_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<bool>,
        Option<S>,
        Option<Vec<create_post::ThreadPostInput<S>>>,
        Option<Datetime>,
        Option<Vec<CreatePostThreadgateRulesItem<S>>>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> CreatePost<S> {
    /// Create a new builder for this type
    pub fn builder() -> CreatePostBuilder<create_post_state::Empty, S> {
        CreatePostBuilder::builder()
    }
}

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

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

impl<St: create_post_state::State, S: BosStr> CreatePostBuilder<St, S> {
    /// Set the `disableQuotePosts` field (optional)
    pub fn disable_quote_posts(mut self, value: impl Into<Option<bool>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `disableQuotePosts` field to an Option value (optional)
    pub fn maybe_disable_quote_posts(mut self, value: Option<bool>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St: create_post_state::State, S: BosStr> CreatePostBuilder<St, S> {
    /// Set the `parentPostId` field (optional)
    pub fn parent_post_id(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `parentPostId` field to an Option value (optional)
    pub fn maybe_parent_post_id(mut self, value: Option<S>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<St, S: BosStr> CreatePostBuilder<St, S>
where
    St: create_post_state::State,
    St::Posts: create_post_state::IsUnset,
{
    /// Set the `posts` field (required)
    pub fn posts(
        mut self,
        value: impl Into<Vec<create_post::ThreadPostInput<S>>>,
    ) -> CreatePostBuilder<create_post_state::SetPosts<St>, S> {
        self._fields.2 = Option::Some(value.into());
        CreatePostBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> CreatePostBuilder<St, S>
where
    St: create_post_state::State,
    St::ScheduledAt: create_post_state::IsUnset,
{
    /// Set the `scheduledAt` field (required)
    pub fn scheduled_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> CreatePostBuilder<create_post_state::SetScheduledAt<St>, S> {
        self._fields.3 = Option::Some(value.into());
        CreatePostBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: create_post_state::State, S: BosStr> CreatePostBuilder<St, S> {
    /// Set the `threadgateRules` field (optional)
    pub fn threadgate_rules(
        mut self,
        value: impl Into<Option<Vec<CreatePostThreadgateRulesItem<S>>>>,
    ) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `threadgateRules` field to an Option value (optional)
    pub fn maybe_threadgate_rules(
        mut self,
        value: Option<Vec<CreatePostThreadgateRulesItem<S>>>,
    ) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St, S: BosStr> CreatePostBuilder<St, S>
where
    St: create_post_state::State,
    St::Posts: create_post_state::IsSet,
    St::ScheduledAt: create_post_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> CreatePost<S> {
        CreatePost {
            disable_quote_posts: self._fields.0,
            parent_post_id: self._fields.1,
            posts: self._fields.2.unwrap(),
            scheduled_at: self._fields.3.unwrap(),
            threadgate_rules: self._fields.4,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(
        self,
        extra_data: BTreeMap<SmolStr, Data<S>>,
    ) -> CreatePost<S> {
        CreatePost {
            disable_quote_posts: self._fields.0,
            parent_post_id: self._fields.1,
            posts: self._fields.2.unwrap(),
            scheduled_at: self._fields.3.unwrap(),
            threadgate_rules: self._fields.4,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_app_chronosky_schedule_createPost() -> 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.chronosky.schedule.createPost"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::XrpcProcedure(LexXrpcProcedure {
                    input: Some(LexXrpcBody {
                        encoding: CowStr::new_static("application/json"),
                        schema: Some(
                            LexXrpcBodySchema::Object(LexObject {
                                required: Some(
                                    vec![
                                        SmolStr::new_static("posts"),
                                        SmolStr::new_static("scheduledAt")
                                    ],
                                ),
                                properties: {
                                    #[allow(unused_mut)]
                                    let mut map = BTreeMap::new();
                                    map.insert(
                                        SmolStr::new_static("disableQuotePosts"),
                                        LexObjectProperty::Boolean(LexBoolean {
                                            ..Default::default()
                                        }),
                                    );
                                    map.insert(
                                        SmolStr::new_static("parentPostId"),
                                        LexObjectProperty::String(LexString {
                                            description: Some(
                                                CowStr::new_static(
                                                    "Chronosky-internal scheduled post ID of the parent post (for scheduling threads or replies). Not an AT Protocol URI or Record Key.",
                                                ),
                                            ),
                                            max_length: Some(100usize),
                                            ..Default::default()
                                        }),
                                    );
                                    map.insert(
                                        SmolStr::new_static("posts"),
                                        LexObjectProperty::Array(LexArray {
                                            description: Some(
                                                CowStr::new_static(
                                                    "Array of posts to schedule (1 element = single post, multiple = thread)",
                                                ),
                                            ),
                                            items: LexArrayItem::Ref(LexRef {
                                                r#ref: CowStr::new_static("#threadPostInput"),
                                                ..Default::default()
                                            }),
                                            min_length: Some(1usize),
                                            max_length: Some(25usize),
                                            ..Default::default()
                                        }),
                                    );
                                    map.insert(
                                        SmolStr::new_static("scheduledAt"),
                                        LexObjectProperty::String(LexString {
                                            description: Some(
                                                CowStr::new_static("Scheduled publish time"),
                                            ),
                                            format: Some(LexStringFormat::Datetime),
                                            max_length: Some(100usize),
                                            ..Default::default()
                                        }),
                                    );
                                    map.insert(
                                        SmolStr::new_static("threadgateRules"),
                                        LexObjectProperty::Array(LexArray {
                                            description: Some(
                                                CowStr::new_static(
                                                    "Thread gate rules to control who can reply",
                                                ),
                                            ),
                                            items: LexArrayItem::Union(LexRefUnion {
                                                refs: vec![
                                                    CowStr::new_static("app.bsky.feed.threadgate#mentionRule"),
                                                    CowStr::new_static("app.bsky.feed.threadgate#followerRule"),
                                                    CowStr::new_static("app.bsky.feed.threadgate#followingRule"),
                                                    CowStr::new_static("app.bsky.feed.threadgate#listRule")
                                                ],
                                                ..Default::default()
                                            }),
                                            max_length: Some(5usize),
                                            ..Default::default()
                                        }),
                                    );
                                    map
                                },
                                ..Default::default()
                            }),
                        ),
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("threadPostInput"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "Individual post input for thread scheduling.",
                        ),
                    ),
                    required: Some(vec![SmolStr::new_static("text")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("createdAt"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Post creation timestamp (optional)"),
                                ),
                                format: Some(LexStringFormat::Datetime),
                                max_length: Some(100usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("embed"),
                            LexObjectProperty::Union(LexRefUnion {
                                description: Some(
                                    CowStr::new_static(
                                        "Embedded content (images, external links, records).",
                                    ),
                                ),
                                refs: vec![
                                    CowStr::new_static("app.bsky.embed.images"),
                                    CowStr::new_static("app.bsky.embed.external"),
                                    CowStr::new_static("app.bsky.embed.record"),
                                    CowStr::new_static("app.bsky.embed.video"),
                                    CowStr::new_static("app.bsky.embed.recordWithMedia")
                                ],
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("facets"),
                            LexObjectProperty::Array(LexArray {
                                description: Some(
                                    CowStr::new_static(
                                        "Rich text facets (mentions, links, tags)",
                                    ),
                                ),
                                items: LexArrayItem::Ref(LexRef {
                                    r#ref: CowStr::new_static("app.bsky.richtext.facet"),
                                    ..Default::default()
                                }),
                                max_length: Some(50usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("labels"),
                            LexObjectProperty::Ref(LexRef {
                                r#ref: CowStr::new_static(
                                    "com.atproto.label.defs#selfLabels",
                                ),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("langs"),
                            LexObjectProperty::Array(LexArray {
                                description: Some(
                                    CowStr::new_static("Language codes (ISO 639-1)"),
                                ),
                                items: LexArrayItem::String(LexString {
                                    format: Some(LexStringFormat::Language),
                                    ..Default::default()
                                }),
                                max_length: Some(3usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("text"),
                            LexObjectProperty::String(LexString {
                                description: Some(CowStr::new_static("Post text content")),
                                max_length: Some(3000usize),
                                max_graphemes: Some(300usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}