// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: com.atproto.label.subscribeLabels
//
// 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::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::com_atproto::label::Label;
use crate::com_atproto::label::subscribe_labels;

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


#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum InfoName<S: BosStr = DefaultStr> {
    OutdatedCursor,
    Other(S),
}

impl<S: BosStr> InfoName<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::OutdatedCursor => "OutdatedCursor",
            Self::Other(s) => s.as_ref(),
        }
    }
    /// Construct from a string-like value, matching known values.
    pub fn from_value(s: S) -> Self {
        match s.as_ref() {
            "OutdatedCursor" => Self::OutdatedCursor,
            _ => Self::Other(s),
        }
    }
}

impl<S: BosStr> core::fmt::Display for InfoName<S> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl<S: BosStr> AsRef<str> for InfoName<S> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<S: BosStr> Serialize for InfoName<S> {
    fn serialize<Ser>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
    where
        Ser: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de, S: Deserialize<'de> + BosStr> Deserialize<'de> for InfoName<S> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = S::deserialize(deserializer)?;
        Ok(Self::from_value(s))
    }
}

impl<S: BosStr + Default> Default for InfoName<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for InfoName<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = InfoName<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            InfoName::OutdatedCursor => InfoName::OutdatedCursor,
            InfoName::Other(v) => InfoName::Other(v.into_static()),
        }
    }
}


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


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct SubscribeLabels {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cursor: Option<i64>,
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub enum SubscribeLabelsMessage<S: BosStr = DefaultStr> {
    #[serde(rename = "#labels")]
    Labels(Box<subscribe_labels::Labels<S>>),
    #[serde(rename = "#info")]
    Info(Box<subscribe_labels::Info<S>>),
}

impl<S: BosStr> SubscribeLabelsMessage<S> {
    /// Decode a framed DAG-CBOR message (header + body).
    pub fn decode_framed<'de>(
        bytes: &'de [u8],
    ) -> Result<SubscribeLabelsMessage<S>, jacquard_common::error::DecodeError>
    where
        S: serde::Deserialize<'de>,
    {
        let (header, body) = jacquard_common::xrpc::subscription::parse_event_header(
            bytes,
        )?;
        match header.t.as_str() {
            "#labels" => {
                let variant = jacquard_common::deps::codegen::serde_ipld_dagcbor::from_slice(
                    body,
                )?;
                Ok(Self::Labels(Box::new(variant)))
            }
            "#info" => {
                let variant = jacquard_common::deps::codegen::serde_ipld_dagcbor::from_slice(
                    body,
                )?;
                Ok(Self::Info(Box::new(variant)))
            }
            unknown => {
                Err(
                    jacquard_common::error::DecodeError::UnknownEventType(unknown.into()),
                )
            }
        }
    }
}


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

#[serde(tag = "error", content = "message")]
pub enum SubscribeLabelsError {
    #[serde(rename = "FutureCursor")]
    FutureCursor(Option<SmolStr>),
    /// Catch-all for unknown error codes.
    #[serde(untagged)]
    Other { error: SmolStr, message: Option<SmolStr> },
}

impl core::fmt::Display for SubscribeLabelsError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::FutureCursor(msg) => {
                write!(f, "FutureCursor")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::Other { error, message } => {
                write!(f, "{}", error)?;
                if let Some(msg) = message {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
        }
    }
}

impl<S: BosStr> LexiconSchema for Info<S> {
    fn nsid() -> &'static str {
        "com.atproto.label.subscribeLabels"
    }
    fn def_name() -> &'static str {
        "info"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_com_atproto_label_subscribeLabels()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for Labels<S> {
    fn nsid() -> &'static str {
        "com.atproto.label.subscribeLabels"
    }
    fn def_name() -> &'static str {
        "labels"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_com_atproto_label_subscribeLabels()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

///Stream response type for
///com.atproto.label.subscribeLabels
pub struct SubscribeLabelsStream;
impl jacquard_common::xrpc::SubscriptionResp for SubscribeLabelsStream {
    const NSID: &'static str = "com.atproto.label.subscribeLabels";
    const ENCODING: jacquard_common::xrpc::MessageEncoding = jacquard_common::xrpc::MessageEncoding::DagCbor;
    type Message<S: BosStr> = SubscribeLabelsMessage<S>;
    type Error = SubscribeLabelsError;
    fn decode_message<'de, S>(
        bytes: &'de [u8],
    ) -> Result<Self::Message<S>, jacquard_common::error::DecodeError>
    where
        S: BosStr + serde::Deserialize<'de>,
        Self::Message<S>: serde::Deserialize<'de>,
    {
        SubscribeLabelsMessage::decode_framed(bytes)
    }
}

impl jacquard_common::xrpc::XrpcSubscription for SubscribeLabels {
    const NSID: &'static str = "com.atproto.label.subscribeLabels";
    const ENCODING: jacquard_common::xrpc::MessageEncoding = jacquard_common::xrpc::MessageEncoding::DagCbor;
    type Stream = SubscribeLabelsStream;
}

pub struct SubscribeLabelsEndpoint;
impl jacquard_common::xrpc::SubscriptionEndpoint for SubscribeLabelsEndpoint {
    const PATH: &'static str = "/xrpc/com.atproto.label.subscribeLabels";
    const ENCODING: jacquard_common::xrpc::MessageEncoding = jacquard_common::xrpc::MessageEncoding::DagCbor;
    type Params<S: BosStr> = SubscribeLabels;
    type Stream = SubscribeLabelsStream;
}

fn lexicon_doc_com_atproto_label_subscribeLabels() -> 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("com.atproto.label.subscribeLabels"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("info"),
                LexUserType::Object(LexObject {
                    required: Some(vec![SmolStr::new_static("name")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("message"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map.insert(
                            SmolStr::new_static("name"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("labels"),
                LexUserType::Object(LexObject {
                    required: Some(
                        vec![SmolStr::new_static("seq"), SmolStr::new_static("labels")],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("labels"),
                            LexObjectProperty::Array(LexArray {
                                items: LexArrayItem::Ref(LexRef {
                                    r#ref: CowStr::new_static("com.atproto.label.defs#label"),
                                    ..Default::default()
                                }),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("seq"),
                            LexObjectProperty::Integer(LexInteger {
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::XrpcSubscription(LexXrpcSubscription {
                    parameters: Some(
                        LexXrpcSubscriptionParameter::Params(LexXrpcParameters {
                            properties: {
                                #[allow(unused_mut)]
                                let mut map = BTreeMap::new();
                                map.insert(
                                    SmolStr::new_static("cursor"),
                                    LexXrpcParametersProperty::Integer(LexInteger {
                                        ..Default::default()
                                    }),
                                );
                                map
                            },
                            ..Default::default()
                        }),
                    ),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod labels_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 Labels;
        type Seq;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Labels = Unset;
        type Seq = Unset;
    }
    ///State transition - sets the `labels` field to Set
    pub struct SetLabels<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetLabels<St> {}
    impl<St: State> State for SetLabels<St> {
        type Labels = Set<members::labels>;
        type Seq = St::Seq;
    }
    ///State transition - sets the `seq` field to Set
    pub struct SetSeq<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetSeq<St> {}
    impl<St: State> State for SetSeq<St> {
        type Labels = St::Labels;
        type Seq = Set<members::seq>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `labels` field
        pub struct labels(());
        ///Marker type for the `seq` field
        pub struct seq(());
    }
}

/// Builder for constructing an instance of this type.
pub struct LabelsBuilder<St: labels_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (Option<Vec<Label<S>>>, Option<i64>),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> Labels<S> {
    /// Create a new builder for this type
    pub fn builder() -> LabelsBuilder<labels_state::Empty, S> {
        LabelsBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> LabelsBuilder<St, S>
where
    St: labels_state::State,
    St::Labels: labels_state::IsUnset,
{
    /// Set the `labels` field (required)
    pub fn labels(
        mut self,
        value: impl Into<Vec<Label<S>>>,
    ) -> LabelsBuilder<labels_state::SetLabels<St>, S> {
        self._fields.0 = Option::Some(value.into());
        LabelsBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> LabelsBuilder<St, S>
where
    St: labels_state::State,
    St::Seq: labels_state::IsUnset,
{
    /// Set the `seq` field (required)
    pub fn seq(
        mut self,
        value: impl Into<i64>,
    ) -> LabelsBuilder<labels_state::SetSeq<St>, S> {
        self._fields.1 = Option::Some(value.into());
        LabelsBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> LabelsBuilder<St, S>
where
    St: labels_state::State,
    St::Labels: labels_state::IsSet,
    St::Seq: labels_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Labels<S> {
        Labels {
            labels: self._fields.0.unwrap(),
            seq: self._fields.1.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>>) -> Labels<S> {
        Labels {
            labels: self._fields.0.unwrap(),
            seq: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

pub mod subscribe_labels_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 {}
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {}
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {}
}

/// Builder for constructing an instance of this type.
pub struct SubscribeLabelsBuilder<St: subscribe_labels_state::State> {
    _state: PhantomData<fn() -> St>,
    _fields: (Option<i64>,),
}

impl SubscribeLabels {
    /// Create a new builder for this type.
    pub fn new() -> SubscribeLabelsBuilder<subscribe_labels_state::Empty> {
        SubscribeLabelsBuilder::new()
    }
}

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

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

impl<St: subscribe_labels_state::State> SubscribeLabelsBuilder<St> {
    /// Set the `cursor` field (optional)
    pub fn cursor(mut self, value: impl Into<Option<i64>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `cursor` field to an Option value (optional)
    pub fn maybe_cursor(mut self, value: Option<i64>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St> SubscribeLabelsBuilder<St>
where
    St: subscribe_labels_state::State,
{
    /// Build the final struct.
    pub fn build(self) -> SubscribeLabels {
        SubscribeLabels {
            cursor: self._fields.0,
        }
    }
}