// @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, 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};
use jacquard_common::types::uri::{RecordUri, UriError};
use jacquard_common::types::value::Data;
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.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct FollowerRule<S: BosStr = DefaultStr> {
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// Allow replies from actors you follow.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct FollowingRule<S: BosStr = DefaultStr> {
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// Allow replies from actors on a list.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct ListRule<S: BosStr = DefaultStr> {
    pub list: AtUri<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// 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.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "app.bsky.feed.threadgate",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Threadgate<S: BosStr = DefaultStr> {
    ///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")]
    pub allow: Option<Vec<ThreadgateAllowItem<S>>>,
    pub created_at: Datetime,
    ///List of hidden reply URIs.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hidden_replies: Option<Vec<AtUri<S>>>,
    ///Reference (AT-URI) to the post record.
    pub post: AtUri<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 ThreadgateAllowItem<S: BosStr = DefaultStr> {
    #[serde(rename = "app.bsky.feed.threadgate#mentionRule")]
    MentionRule(Box<threadgate::MentionRule<S>>),
    #[serde(rename = "app.bsky.feed.threadgate#followerRule")]
    FollowerRule(Box<threadgate::FollowerRule<S>>),
    #[serde(rename = "app.bsky.feed.threadgate#followingRule")]
    FollowingRule(Box<threadgate::FollowingRule<S>>),
    #[serde(rename = "app.bsky.feed.threadgate#listRule")]
    ListRule(Box<threadgate::ListRule<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 ThreadgateGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Threadgate<S>,
}

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

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct MentionRule<S: BosStr = DefaultStr> {
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

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

impl<S: BosStr> LexiconSchema for FollowerRule<S> {
    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<S: BosStr> LexiconSchema for FollowingRule<S> {
    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<S: BosStr> LexiconSchema for ListRule<S> {
    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<S: BosStr> = ThreadgateGetRecordOutput<S>;
    type Err = RecordError;
}

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

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

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

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

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

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

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

impl<St, S: BosStr> ListRuleBuilder<St, S>
where
    St: list_rule_state::State,
    St::List: list_rule_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> ListRule<S> {
        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<SmolStr, Data<S>>) -> ListRule<S> {
        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<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetCreatedAt<St> {}
    impl<St: State> State for SetCreatedAt<St> {
        type CreatedAt = Set<members::created_at>;
        type Post = St::Post;
    }
    ///State transition - sets the `post` field to Set
    pub struct SetPost<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetPost<St> {}
    impl<St: State> State for SetPost<St> {
        type CreatedAt = St::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<St: threadgate_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Vec<ThreadgateAllowItem<S>>>,
        Option<Datetime>,
        Option<Vec<AtUri<S>>>,
        Option<AtUri<S>>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

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

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

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

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

impl<St, S: BosStr> ThreadgateBuilder<St, S>
where
    St: threadgate_state::State,
    St::CreatedAt: threadgate_state::IsSet,
    St::Post: threadgate_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Threadgate<S> {
        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<SmolStr, Data<S>>,
    ) -> Threadgate<S> {
        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),
        }
    }
}