// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: app.chronosky.schedule.updatePost
//
// This file was automatically generated from Lexicon schemas.
// Any manual changes will be overwritten on the next regeneration.

#[allow(unused_imports)]
use alloc::collections::BTreeMap;

#[allow(unused_imports)]
use core::marker::PhantomData;
use jacquard_common::CowStr;

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
use jacquard_common::types::blob::BlobRef;
use jacquard_common::types::string::{Datetime, Language};
use jacquard_derive::{IntoStatic, lexicon, open_union};
use jacquard_lexicon::lexicon::LexiconDoc;
use jacquard_lexicon::schema::LexiconSchema;

#[allow(unused_imports)]
use jacquard_lexicon::validation::{ConstraintError, ValidationPath};
use serde::{Serialize, Deserialize};
use crate::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::app_chronosky::schedule::list_posts::ScheduledPost;
use crate::com_atproto::label::SelfLabels;
use crate::app_chronosky::schedule::update_post;
/// Image reference that supports both new blob uploads and existing image CID references.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct ImageRef<'a> {
    ///Alt text for the image.
    #[serde(borrow)]
    pub alt: CowStr<'a>,
    ///CID of an image blob. Can reference an existing image in the post or a newly uploaded image via media.uploadBlob.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub cid: Option<CowStr<'a>>,
    ///New image blob (for newly uploaded images).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub image: Option<BlobRef<'a>>,
}

/// Images embed that supports CID references for existing images.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct ImagesEmbed<'a> {
    #[serde(borrow)]
    pub images: Vec<update_post::ImageRef<'a>>,
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct UpdatePost<'a> {
    ///Whether to disable quote posts
    #[serde(skip_serializing_if = "Option::is_none")]
    pub disable_quote_posts: Option<bool>,
    ///Embedded content (images, external links, records). Use #imagesEmbed to reference existing images by CID.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub embed: Option<UpdatePostEmbed<'a>>,
    ///Rich text facets (links, mentions, tags).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub facets: Option<Vec<Facet<'a>>>,
    ///Post ID to update.
    #[serde(borrow)]
    pub id: CowStr<'a>,
    ///Self-applied content labels for content warnings (AT Protocol standard).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub labels: Option<SelfLabels<'a>>,
    ///Language codes (ISO 639-1).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub langs: Option<Vec<Language>>,
    ///New scheduled publication datetime (ISO 8601).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scheduled_at: Option<Datetime>,
    ///New post text content.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub text: Option<CowStr<'a>>,
    ///Thread gate rules to control who can reply
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub threadgate_rules: Option<Vec<UpdatePostThreadgateRulesItem<'a>>>,
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type")]
#[serde(bound(deserialize = "'de: 'a"))]
pub enum UpdatePostEmbed<'a> {
    #[serde(rename = "app.chronosky.schedule.updatePost#imagesEmbed")]
    ImagesEmbed(Box<update_post::ImagesEmbed<'a>>),
    #[serde(rename = "app.bsky.embed.images")]
    Images(Box<Images<'a>>),
    #[serde(rename = "app.bsky.embed.external")]
    External(Box<ExternalRecord<'a>>),
    #[serde(rename = "app.bsky.embed.record")]
    Record(Box<Record<'a>>),
    #[serde(rename = "app.bsky.embed.video")]
    Video(Box<Video<'a>>),
    #[serde(rename = "app.bsky.embed.recordWithMedia")]
    RecordWithMedia(Box<RecordWithMedia<'a>>),
}


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


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct UpdatePostOutput<'a> {
    #[serde(borrow)]
    pub post: ScheduledPost<'a>,
}


#[open_union]
#[derive(
    Serialize,
    Deserialize,
    Debug,
    Clone,
    PartialEq,
    Eq,
    thiserror::Error,
    miette::Diagnostic,
    IntoStatic
)]

#[serde(tag = "error", content = "message")]
#[serde(bound(deserialize = "'de: 'a"))]
pub enum UpdatePostError<'a> {
    #[serde(rename = "PostNotFound")]
    PostNotFound(Option<CowStr<'a>>),
    #[serde(rename = "PostNotPending")]
    PostNotPending(Option<CowStr<'a>>),
    #[serde(rename = "NoFieldsProvided")]
    NoFieldsProvided(Option<CowStr<'a>>),
}

impl core::fmt::Display for UpdatePostError<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::PostNotFound(msg) => {
                write!(f, "PostNotFound")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::PostNotPending(msg) => {
                write!(f, "PostNotPending")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::NoFieldsProvided(msg) => {
                write!(f, "NoFieldsProvided")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::Unknown(err) => write!(f, "Unknown error: {:?}", err),
        }
    }
}

impl<'a> LexiconSchema for ImageRef<'a> {
    fn nsid() -> &'static str {
        "app.chronosky.schedule.updatePost"
    }
    fn def_name() -> &'static str {
        "imageRef"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_chronosky_schedule_updatePost()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.alt;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 1000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("alt"),
                    max: 1000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.cid {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 200usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("cid"),
                    max: 200usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.image {
            {
                let size = value.blob().size;
                if size > 1000000usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("image"),
                        max: 1000000usize,
                        actual: size,
                    });
                }
            }
        }
        if let Some(ref value) = self.image {
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &[
                    "image/jpeg",
                    "image/png",
                    "image/webp",
                    "image/gif",
                ];
                let matched = accepted
                    .iter()
                    .any(|pattern| {
                        if *pattern == "*/*" {
                            true
                        } else if pattern.ends_with("/*") {
                            let prefix = &pattern[..pattern.len() - 2];
                            mime.starts_with(prefix)
                                && mime.as_bytes().get(prefix.len()) == Some(&b'/')
                        } else {
                            mime == *pattern
                        }
                    });
                if !matched {
                    return Err(ConstraintError::BlobMimeTypeNotAccepted {
                        path: ValidationPath::from_field("image"),
                        accepted: vec![
                            "image/jpeg".to_string(), "image/png".to_string(),
                            "image/webp".to_string(), "image/gif".to_string()
                        ],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        Ok(())
    }
}

impl<'a> LexiconSchema for ImagesEmbed<'a> {
    fn nsid() -> &'static str {
        "app.chronosky.schedule.updatePost"
    }
    fn def_name() -> &'static str {
        "imagesEmbed"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_chronosky_schedule_updatePost()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.images;
            #[allow(unused_comparisons)]
            if value.len() > 4usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("images"),
                    max: 4usize,
                    actual: value.len(),
                });
            }
        }
        Ok(())
    }
}

/// Response type for app.chronosky.schedule.updatePost
pub struct UpdatePostResponse;
impl jacquard_common::xrpc::XrpcResp for UpdatePostResponse {
    const NSID: &'static str = "app.chronosky.schedule.updatePost";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = UpdatePostOutput<'de>;
    type Err<'de> = UpdatePostError<'de>;
}

impl<'a> jacquard_common::xrpc::XrpcRequest for UpdatePost<'a> {
    const NSID: &'static str = "app.chronosky.schedule.updatePost";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Procedure(
        "application/json",
    );
    type Response = UpdatePostResponse;
}

/// Endpoint type for app.chronosky.schedule.updatePost
pub struct UpdatePostRequest;
impl jacquard_common::xrpc::XrpcEndpoint for UpdatePostRequest {
    const PATH: &'static str = "/xrpc/app.chronosky.schedule.updatePost";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Procedure(
        "application/json",
    );
    type Request<'de> = UpdatePost<'de>;
    type Response = UpdatePostResponse;
}

fn lexicon_doc_app_chronosky_schedule_updatePost() -> 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.updatePost"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("imageRef"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "Image reference that supports both new blob uploads and existing image CID references.",
                        ),
                    ),
                    required: Some(vec![SmolStr::new_static("alt")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("alt"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Alt text for the image."),
                                ),
                                max_length: Some(1000usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("cid"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "CID of an image blob. Can reference an existing image in the post or a newly uploaded image via media.uploadBlob.",
                                    ),
                                ),
                                max_length: Some(200usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("image"),
                            LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("imagesEmbed"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "Images embed that supports CID references for existing images.",
                        ),
                    ),
                    required: Some(vec![SmolStr::new_static("images")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("images"),
                            LexObjectProperty::Array(LexArray {
                                items: LexArrayItem::Ref(LexRef {
                                    r#ref: CowStr::new_static("#imageRef"),
                                    ..Default::default()
                                }),
                                max_length: Some(4usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            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("id")]),
                                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("embed"),
                                        LexObjectProperty::Union(LexRefUnion {
                                            description: Some(
                                                CowStr::new_static(
                                                    "Embedded content (images, external links, records). Use #imagesEmbed to reference existing images by CID.",
                                                ),
                                            ),
                                            refs: vec![
                                                CowStr::new_static("#imagesEmbed"),
                                                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 (links, mentions, tags).",
                                                ),
                                            ),
                                            items: LexArrayItem::Ref(LexRef {
                                                r#ref: CowStr::new_static("app.bsky.richtext.facet"),
                                                ..Default::default()
                                            }),
                                            ..Default::default()
                                        }),
                                    );
                                    map.insert(
                                        SmolStr::new_static("id"),
                                        LexObjectProperty::String(LexString {
                                            description: Some(CowStr::new_static("Post ID to update.")),
                                            max_length: Some(100usize),
                                            ..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("scheduledAt"),
                                        LexObjectProperty::String(LexString {
                                            description: Some(
                                                CowStr::new_static(
                                                    "New scheduled publication datetime (ISO 8601).",
                                                ),
                                            ),
                                            format: Some(LexStringFormat::Datetime),
                                            max_length: Some(100usize),
                                            ..Default::default()
                                        }),
                                    );
                                    map.insert(
                                        SmolStr::new_static("text"),
                                        LexObjectProperty::String(LexString {
                                            description: Some(
                                                CowStr::new_static("New post text content."),
                                            ),
                                            max_length: Some(3000usize),
                                            max_graphemes: Some(300usize),
                                            ..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
        },
        ..Default::default()
    }
}

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

/// Builder for constructing an instance of this type
pub struct ImagesEmbedBuilder<'a, S: images_embed_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (Option<Vec<update_post::ImageRef<'a>>>,),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> ImagesEmbed<'a> {
    /// Create a new builder for this type
    pub fn new() -> ImagesEmbedBuilder<'a, images_embed_state::Empty> {
        ImagesEmbedBuilder::new()
    }
}

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

impl<'a, S> ImagesEmbedBuilder<'a, S>
where
    S: images_embed_state::State,
    S::Images: images_embed_state::IsUnset,
{
    /// Set the `images` field (required)
    pub fn images(
        mut self,
        value: impl Into<Vec<update_post::ImageRef<'a>>>,
    ) -> ImagesEmbedBuilder<'a, images_embed_state::SetImages<S>> {
        self._fields.0 = Option::Some(value.into());
        ImagesEmbedBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> ImagesEmbedBuilder<'a, S>
where
    S: images_embed_state::State,
    S::Images: images_embed_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> ImagesEmbed<'a> {
        ImagesEmbed {
            images: 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>,
        >,
    ) -> ImagesEmbed<'a> {
        ImagesEmbed {
            images: self._fields.0.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}