// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: app.bsky.feed.threadgate
//
// 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};
use jacquard_common::types::uri::{RecordUri, UriError};
use jacquard_common::xrpc::XrpcResp;
use jacquard_derive::{IntoStatic, lexicon, open_union};
use jacquard_lexicon::lexicon::LexiconDoc;
use jacquard_lexicon::schema::LexiconSchema;

#[allow(unused_imports)]
use jacquard_lexicon::validation::{ConstraintError, ValidationPath};
use serde::{Serialize, Deserialize};
use crate::app_bsky::feed::threadgate;
/// Allow replies from actors who follow you.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct FollowerRule<'a> {}
/// Allow replies from actors you follow.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct FollowingRule<'a> {}
/// Allow replies from actors on a list.

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

/// Record defining interaction gating rules for a thread (aka, reply controls). The record key (rkey) of the threadgate record must match the record key of the thread's root post, and that record must be in the same repository.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Threadgate<'a> {
    ///List of rules defining who can reply to this post. If value is an empty array, no one can reply. If value is undefined, anyone can reply.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub allow: Option<Vec<ThreadgateAllowItem<'a>>>,
    pub created_at: Datetime,
    ///List of hidden reply URIs.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub hidden_replies: Option<Vec<AtUri<'a>>>,
    ///Reference (AT-URI) to the post record.
    #[serde(borrow)]
    pub post: AtUri<'a>,
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type")]
#[serde(bound(deserialize = "'de: 'a"))]
pub enum ThreadgateAllowItem<'a> {
    #[serde(rename = "app.bsky.feed.threadgate#mentionRule")]
    MentionRule(Box<threadgate::MentionRule<'a>>),
    #[serde(rename = "app.bsky.feed.threadgate#followerRule")]
    FollowerRule(Box<threadgate::FollowerRule<'a>>),
    #[serde(rename = "app.bsky.feed.threadgate#followingRule")]
    FollowingRule(Box<threadgate::FollowingRule<'a>>),
    #[serde(rename = "app.bsky.feed.threadgate#listRule")]
    ListRule(Box<threadgate::ListRule<'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 ThreadgateGetRecordOutput<'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: Threadgate<'a>,
}

/// Allow replies from actors mentioned in your post.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct MentionRule<'a> {}
impl<'a> Threadgate<'a> {
    pub fn uri(
        uri: impl Into<CowStr<'a>>,
    ) -> Result<RecordUri<'a, ThreadgateRecord>, UriError> {
        RecordUri::try_from_uri(AtUri::new_cow(uri.into())?)
    }
}

impl<'a> LexiconSchema for FollowerRule<'a> {
    fn nsid() -> &'static str {
        "app.bsky.feed.threadgate"
    }
    fn def_name() -> &'static str {
        "followerRule"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_bsky_feed_threadgate()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

impl<'a> LexiconSchema for FollowingRule<'a> {
    fn nsid() -> &'static str {
        "app.bsky.feed.threadgate"
    }
    fn def_name() -> &'static str {
        "followingRule"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_bsky_feed_threadgate()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

impl<'a> LexiconSchema for ListRule<'a> {
    fn nsid() -> &'static str {
        "app.bsky.feed.threadgate"
    }
    fn def_name() -> &'static str {
        "listRule"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_bsky_feed_threadgate()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

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

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

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

impl Collection for Threadgate<'_> {
    const NSID: &'static str = "app.bsky.feed.threadgate";
    type Record = ThreadgateRecord;
}

impl Collection for ThreadgateRecord {
    const NSID: &'static str = "app.bsky.feed.threadgate";
    type Record = ThreadgateRecord;
}

impl<'a> LexiconSchema for Threadgate<'a> {
    fn nsid() -> &'static str {
        "app.bsky.feed.threadgate"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_bsky_feed_threadgate()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.allow {
            #[allow(unused_comparisons)]
            if value.len() > 5usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("allow"),
                    max: 5usize,
                    actual: value.len(),
                });
            }
        }
        if let Some(ref value) = self.hidden_replies {
            #[allow(unused_comparisons)]
            if value.len() > 300usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("hidden_replies"),
                    max: 300usize,
                    actual: value.len(),
                });
            }
        }
        Ok(())
    }
}

impl<'a> LexiconSchema for MentionRule<'a> {
    fn nsid() -> &'static str {
        "app.bsky.feed.threadgate"
    }
    fn def_name() -> &'static str {
        "mentionRule"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_bsky_feed_threadgate()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

fn lexicon_doc_app_bsky_feed_threadgate() -> 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.bsky.feed.threadgate"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("followerRule"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static("Allow replies from actors who follow you."),
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("followingRule"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static("Allow replies from actors you follow."),
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("listRule"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static("Allow replies from actors on a list."),
                    ),
                    required: Some(vec![SmolStr::new_static("list")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("list"),
                            LexObjectProperty::String(LexString {
                                format: Some(LexStringFormat::AtUri),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "Record defining interaction gating rules for a thread (aka, reply controls). The record key (rkey) of the threadgate record must match the record key of the thread's root post, and that record must be in the same repository.",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("post"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("allow"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "List of rules defining who can reply to this post. If value is an empty array, no one can reply. If value is undefined, anyone can reply.",
                                        ),
                                    ),
                                    items: LexArrayItem::Union(LexRefUnion {
                                        refs: vec![
                                            CowStr::new_static("#mentionRule"),
                                            CowStr::new_static("#followerRule"),
                                            CowStr::new_static("#followingRule"),
                                            CowStr::new_static("#listRule")
                                        ],
                                        ..Default::default()
                                    }),
                                    max_length: Some(5usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("hiddenReplies"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static("List of hidden reply URIs."),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        format: Some(LexStringFormat::AtUri),
                                        ..Default::default()
                                    }),
                                    max_length: Some(300usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("post"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Reference (AT-URI) to the post record."),
                                    ),
                                    format: Some(LexStringFormat::AtUri),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("mentionRule"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "Allow replies from actors mentioned in your post.",
                        ),
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

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

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

impl<'a> ListRule<'a> {
    /// Create a new builder for this type
    pub fn new() -> ListRuleBuilder<'a, list_rule_state::Empty> {
        ListRuleBuilder::new()
    }
}

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

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

impl<'a, S> ListRuleBuilder<'a, S>
where
    S: list_rule_state::State,
    S::List: list_rule_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> ListRule<'a> {
        ListRule {
            list: 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>,
        >,
    ) -> ListRule<'a> {
        ListRule {
            list: self._fields.0.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

pub mod threadgate_state {

    pub use crate::builder_types::{Set, Unset, IsSet, IsUnset};
    #[allow(unused)]
    use ::core::marker::PhantomData;
    mod sealed {
        pub trait Sealed {}
    }
    /// State trait tracking which required fields have been set
    pub trait State: sealed::Sealed {
        type CreatedAt;
        type Post;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedAt = Unset;
        type Post = Unset;
    }
    ///State transition - sets the `created_at` field to Set
    pub struct SetCreatedAt<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetCreatedAt<S> {}
    impl<S: State> State for SetCreatedAt<S> {
        type CreatedAt = Set<members::created_at>;
        type Post = S::Post;
    }
    ///State transition - sets the `post` field to Set
    pub struct SetPost<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetPost<S> {}
    impl<S: State> State for SetPost<S> {
        type CreatedAt = S::CreatedAt;
        type Post = Set<members::post>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `post` field
        pub struct post(());
    }
}

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

impl<'a> Threadgate<'a> {
    /// Create a new builder for this type
    pub fn new() -> ThreadgateBuilder<'a, threadgate_state::Empty> {
        ThreadgateBuilder::new()
    }
}

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

impl<'a, S: threadgate_state::State> ThreadgateBuilder<'a, S> {
    /// Set the `allow` field (optional)
    pub fn allow(
        mut self,
        value: impl Into<Option<Vec<ThreadgateAllowItem<'a>>>>,
    ) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `allow` field to an Option value (optional)
    pub fn maybe_allow(mut self, value: Option<Vec<ThreadgateAllowItem<'a>>>) -> Self {
        self._fields.0 = value;
        self
    }
}

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

impl<'a, S: threadgate_state::State> ThreadgateBuilder<'a, S> {
    /// Set the `hiddenReplies` field (optional)
    pub fn hidden_replies(mut self, value: impl Into<Option<Vec<AtUri<'a>>>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `hiddenReplies` field to an Option value (optional)
    pub fn maybe_hidden_replies(mut self, value: Option<Vec<AtUri<'a>>>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<'a, S> ThreadgateBuilder<'a, S>
where
    S: threadgate_state::State,
    S::Post: threadgate_state::IsUnset,
{
    /// Set the `post` field (required)
    pub fn post(
        mut self,
        value: impl Into<AtUri<'a>>,
    ) -> ThreadgateBuilder<'a, threadgate_state::SetPost<S>> {
        self._fields.3 = Option::Some(value.into());
        ThreadgateBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> ThreadgateBuilder<'a, S>
where
    S: threadgate_state::State,
    S::CreatedAt: threadgate_state::IsSet,
    S::Post: threadgate_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Threadgate<'a> {
        Threadgate {
            allow: self._fields.0,
            created_at: self._fields.1.unwrap(),
            hidden_replies: self._fields.2,
            post: self._fields.3.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>,
        >,
    ) -> Threadgate<'a> {
        Threadgate {
            allow: self._fields.0,
            created_at: self._fields.1.unwrap(),
            hidden_replies: self._fields.2,
            post: self._fields.3.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}