// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: sh.weaver.collab.invite
//
// 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::{Did, AtUri, Cid, Datetime};
use jacquard_common::types::uri::{RecordUri, UriError};
use jacquard_common::xrpc::XrpcResp;
use jacquard_derive::{IntoStatic, lexicon};
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::repo::strong_ref::StrongRef;
use crate::sh_weaver::collab::invite;
/// The scope/type of collaboration.

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CollabScope<'a> {
    ShWeaverCollabDefsNotebook,
    ShWeaverCollabDefsEntry,
    ShWeaverCollabDefsChapter,
    Other(CowStr<'a>),
}

impl<'a> CollabScope<'a> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::ShWeaverCollabDefsNotebook => "sh.weaver.collab.defs#notebook",
            Self::ShWeaverCollabDefsEntry => "sh.weaver.collab.defs#entry",
            Self::ShWeaverCollabDefsChapter => "sh.weaver.collab.defs#chapter",
            Self::Other(s) => s.as_ref(),
        }
    }
}

impl<'a> From<&'a str> for CollabScope<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "sh.weaver.collab.defs#notebook" => Self::ShWeaverCollabDefsNotebook,
            "sh.weaver.collab.defs#entry" => Self::ShWeaverCollabDefsEntry,
            "sh.weaver.collab.defs#chapter" => Self::ShWeaverCollabDefsChapter,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for CollabScope<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "sh.weaver.collab.defs#notebook" => Self::ShWeaverCollabDefsNotebook,
            "sh.weaver.collab.defs#entry" => Self::ShWeaverCollabDefsEntry,
            "sh.weaver.collab.defs#chapter" => Self::ShWeaverCollabDefsChapter,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

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

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

impl<'a> serde::Serialize for CollabScope<'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 CollabScope<'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 jacquard_common::IntoStatic for CollabScope<'_> {
    type Output = CollabScope<'static>;
    fn into_static(self) -> Self::Output {
        match self {
            CollabScope::ShWeaverCollabDefsNotebook => {
                CollabScope::ShWeaverCollabDefsNotebook
            }
            CollabScope::ShWeaverCollabDefsEntry => CollabScope::ShWeaverCollabDefsEntry,
            CollabScope::ShWeaverCollabDefsChapter => {
                CollabScope::ShWeaverCollabDefsChapter
            }
            CollabScope::Other(v) => CollabScope::Other(v.into_static()),
        }
    }
}

/// Invitation to collaborate on a resource (notebook, entry, chapter, etc.). Creates half of a two-way agreement.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Invite<'a> {
    pub created_at: Datetime,
    ///Optional expiration for the invite.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<Datetime>,
    ///DID of the user being invited.
    #[serde(borrow)]
    pub invitee: Did<'a>,
    ///Optional message to the invitee.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub message: Option<CowStr<'a>>,
    ///The resource to collaborate on (notebook, entry, chapter, etc.).
    #[serde(borrow)]
    pub resource: StrongRef<'a>,
    ///Optional explicit scope type. If omitted, inferred from resource lexicon.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub scope: Option<invite::CollabScope<'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 InviteGetRecordOutput<'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: Invite<'a>,
}

impl<'a> Invite<'a> {
    pub fn uri(
        uri: impl Into<CowStr<'a>>,
    ) -> Result<RecordUri<'a, InviteRecord>, UriError> {
        RecordUri::try_from_uri(AtUri::new_cow(uri.into())?)
    }
}

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

#[derive(Debug, Serialize, Deserialize)]
pub struct InviteRecord;
impl XrpcResp for InviteRecord {
    const NSID: &'static str = "sh.weaver.collab.invite";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = InviteGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Invite<'_> {
    const NSID: &'static str = "sh.weaver.collab.invite";
    type Record = InviteRecord;
}

impl Collection for InviteRecord {
    const NSID: &'static str = "sh.weaver.collab.invite";
    type Record = InviteRecord;
}

impl<'a> LexiconSchema for Invite<'a> {
    fn nsid() -> &'static str {
        "sh.weaver.collab.invite"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_sh_weaver_collab_invite()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.message {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 3000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("message"),
                    max: 3000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.message {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 300usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("message"),
                        max: 300usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

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

/// Builder for constructing an instance of this type
pub struct InviteBuilder<'a, S: invite_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Datetime>,
        Option<Datetime>,
        Option<Did<'a>>,
        Option<CowStr<'a>>,
        Option<StrongRef<'a>>,
        Option<invite::CollabScope<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Invite<'a> {
    /// Create a new builder for this type
    pub fn new() -> InviteBuilder<'a, invite_state::Empty> {
        InviteBuilder::new()
    }
}

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

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

impl<'a, S: invite_state::State> InviteBuilder<'a, S> {
    /// Set the `expiresAt` field (optional)
    pub fn expires_at(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `expiresAt` field to an Option value (optional)
    pub fn maybe_expires_at(mut self, value: Option<Datetime>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<'a, S> InviteBuilder<'a, S>
where
    S: invite_state::State,
    S::Invitee: invite_state::IsUnset,
{
    /// Set the `invitee` field (required)
    pub fn invitee(
        mut self,
        value: impl Into<Did<'a>>,
    ) -> InviteBuilder<'a, invite_state::SetInvitee<S>> {
        self._fields.2 = Option::Some(value.into());
        InviteBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: invite_state::State> InviteBuilder<'a, S> {
    /// Set the `message` field (optional)
    pub fn message(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `message` field to an Option value (optional)
    pub fn maybe_message(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<'a, S> InviteBuilder<'a, S>
where
    S: invite_state::State,
    S::Resource: invite_state::IsUnset,
{
    /// Set the `resource` field (required)
    pub fn resource(
        mut self,
        value: impl Into<StrongRef<'a>>,
    ) -> InviteBuilder<'a, invite_state::SetResource<S>> {
        self._fields.4 = Option::Some(value.into());
        InviteBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: invite_state::State> InviteBuilder<'a, S> {
    /// Set the `scope` field (optional)
    pub fn scope(mut self, value: impl Into<Option<invite::CollabScope<'a>>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `scope` field to an Option value (optional)
    pub fn maybe_scope(mut self, value: Option<invite::CollabScope<'a>>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<'a, S> InviteBuilder<'a, S>
where
    S: invite_state::State,
    S::Resource: invite_state::IsSet,
    S::Invitee: invite_state::IsSet,
    S::CreatedAt: invite_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Invite<'a> {
        Invite {
            created_at: self._fields.0.unwrap(),
            expires_at: self._fields.1,
            invitee: self._fields.2.unwrap(),
            message: self._fields.3,
            resource: self._fields.4.unwrap(),
            scope: self._fields.5,
            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>,
        >,
    ) -> Invite<'a> {
        Invite {
            created_at: self._fields.0.unwrap(),
            expires_at: self._fields.1,
            invitee: self._fields.2.unwrap(),
            message: self._fields.3,
            resource: self._fields.4.unwrap(),
            scope: self._fields.5,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_sh_weaver_collab_invite() -> 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("sh.weaver.collab.invite"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("collabScope"),
                LexUserType::String(LexString {
                    description: Some(
                        CowStr::new_static("The scope/type of collaboration."),
                    ),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "Invitation to collaborate on a resource (notebook, entry, chapter, etc.). Creates half of a two-way agreement.",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("resource"),
                                SmolStr::new_static("invitee"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("expiresAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Optional expiration for the invite."),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("invitee"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("DID of the user being invited."),
                                    ),
                                    format: Some(LexStringFormat::Did),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("message"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Optional message to the invitee."),
                                    ),
                                    max_length: Some(3000usize),
                                    max_graphemes: Some(300usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("resource"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("com.atproto.repo.strongRef"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("scope"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("#collabScope"),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}