// @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;

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
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::com_atproto::label::Label;
use crate::com_atproto::label::subscribe_labels;

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct Info<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub message: Option<CowStr<'a>>,
    #[serde(borrow)]
    pub name: InfoName<'a>,
}


#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum InfoName<'a> {
    OutdatedCursor,
    Other(CowStr<'a>),
}

impl<'a> InfoName<'a> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::OutdatedCursor => "OutdatedCursor",
            Self::Other(s) => s.as_ref(),
        }
    }
}

impl<'a> From<&'a str> for InfoName<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "OutdatedCursor" => Self::OutdatedCursor,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for InfoName<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "OutdatedCursor" => Self::OutdatedCursor,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

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

impl<'a> AsRef<str> for InfoName<'a> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

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

impl<'de, 'a> serde::Deserialize<'de> for InfoName<'a>
where
    'de: 'a,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = <&'de str>::deserialize(deserializer)?;
        Ok(Self::from(s))
    }
}

impl<'a> Default for InfoName<'a> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl jacquard_common::IntoStatic for InfoName<'_> {
    type Output = InfoName<'static>;
    fn into_static(self) -> Self::Output {
        match self {
            InfoName::OutdatedCursor => InfoName::OutdatedCursor,
            InfoName::Other(v) => InfoName::Other(v.into_static()),
        }
    }
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Labels<'a> {
    #[serde(borrow)]
    pub labels: Vec<Label<'a>>,
    pub seq: i64,
}


#[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")]
#[serde(bound(deserialize = "'de: 'a"))]
pub enum SubscribeLabelsMessage<'a> {
    #[serde(rename = "#labels")]
    Labels(Box<subscribe_labels::Labels<'a>>),
    #[serde(rename = "#info")]
    Info(Box<subscribe_labels::Info<'a>>),
}

impl<'a> SubscribeLabelsMessage<'a> {
    /// Decode a framed DAG-CBOR message (header + body).
    pub fn decode_framed<'de: 'a>(
        bytes: &'de [u8],
    ) -> Result<SubscribeLabelsMessage<'a>, jacquard_common::error::DecodeError> {
        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()),
                )
            }
        }
    }
}


#[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 SubscribeLabelsError<'a> {
    #[serde(rename = "FutureCursor")]
    FutureCursor(Option<CowStr<'a>>),
}

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::Unknown(err) => write!(f, "Unknown error: {:?}", err),
        }
    }
}

impl<'a> LexiconSchema for Info<'a> {
    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<'a> LexiconSchema for Labels<'a> {
    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<'de> = SubscribeLabelsMessage<'de>;
    type Error<'de> = SubscribeLabelsError<'de>;
    fn decode_message<'de>(
        bytes: &'de [u8],
    ) -> Result<Self::Message<'de>, jacquard_common::error::DecodeError> {
        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<'de> = 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<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetLabels<S> {}
    impl<S: State> State for SetLabels<S> {
        type Labels = Set<members::labels>;
        type Seq = S::Seq;
    }
    ///State transition - sets the `seq` field to Set
    pub struct SetSeq<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetSeq<S> {}
    impl<S: State> State for SetSeq<S> {
        type Labels = S::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<'a, S: labels_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (Option<Vec<Label<'a>>>, Option<i64>),
    _lifetime: PhantomData<&'a ()>,
}

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

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

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

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

impl<'a, S> LabelsBuilder<'a, S>
where
    S: labels_state::State,
    S::Labels: labels_state::IsSet,
    S::Seq: labels_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Labels<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Labels<'a> {
        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<S: subscribe_labels_state::State> {
    _state: PhantomData<fn() -> S>,
    _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
    pub fn new() -> Self {
        SubscribeLabelsBuilder {
            _state: PhantomData,
            _fields: (None,),
        }
    }
}

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