// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: org.hypercerts.helper.workScopeTag
//
// 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::com_atproto::repo::strong_ref::StrongRef;
use crate::org_hypercerts::SmallBlob;
use crate::org_hypercerts::Uri;
/// A reusable scope atom for work scope logic expressions. Scopes can represent topics, languages, domains, deliverables, methods, regions, tags, or other categorical labels.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct WorkScopeTag<'a> {
    ///Optional array of alternative names or identifiers for this scope.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub aliases: Option<Vec<CowStr<'a>>>,
    ///Client-declared timestamp when this record was originally created
    pub created_at: Datetime,
    ///Optional longer description of this scope.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub description: Option<CowStr<'a>>,
    ///Optional external reference for this scope as a URI or blob.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub external_reference: Option<WorkScopeTagExternalReference<'a>>,
    ///Lowercase, hyphenated machine-readable key for this scope (e.g., 'ipfs', 'go-lang', 'filecoin').
    #[serde(borrow)]
    pub key: CowStr<'a>,
    ///Category type of this scope. Recommended values: topic, language, domain, method, tag.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub kind: Option<CowStr<'a>>,
    ///Human-readable label for this scope.
    #[serde(borrow)]
    pub label: CowStr<'a>,
    ///Optional strong reference to a parent scope record for taxonomy/hierarchy support.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub parent: Option<StrongRef<'a>>,
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type")]
#[serde(bound(deserialize = "'de: 'a"))]
pub enum WorkScopeTagExternalReference<'a> {
    #[serde(rename = "org.hypercerts.defs#uri")]
    Uri(Box<Uri<'a>>),
    #[serde(rename = "org.hypercerts.defs#smallBlob")]
    SmallBlob(Box<SmallBlob<'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 WorkScopeTagGetRecordOutput<'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: WorkScopeTag<'a>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct WorkScopeTagRecord;
impl XrpcResp for WorkScopeTagRecord {
    const NSID: &'static str = "org.hypercerts.helper.workScopeTag";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = WorkScopeTagGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for WorkScopeTag<'_> {
    const NSID: &'static str = "org.hypercerts.helper.workScopeTag";
    type Record = WorkScopeTagRecord;
}

impl Collection for WorkScopeTagRecord {
    const NSID: &'static str = "org.hypercerts.helper.workScopeTag";
    type Record = WorkScopeTagRecord;
}

impl<'a> LexiconSchema for WorkScopeTag<'a> {
    fn nsid() -> &'static str {
        "org.hypercerts.helper.workScopeTag"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_org_hypercerts_helper_workScopeTag()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.aliases {
            #[allow(unused_comparisons)]
            if value.len() > 50usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("aliases"),
                    max: 50usize,
                    actual: value.len(),
                });
            }
        }
        if let Some(ref value) = self.description {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 10000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("description"),
                    max: 10000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.description {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 1000usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("description"),
                        max: 1000usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let value = &self.key;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 120usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("key"),
                    max: 120usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.kind {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 50usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("kind"),
                    max: 50usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.label;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 200usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("label"),
                    max: 200usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

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

/// Builder for constructing an instance of this type
pub struct WorkScopeTagBuilder<'a, S: work_scope_tag_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Vec<CowStr<'a>>>,
        Option<Datetime>,
        Option<CowStr<'a>>,
        Option<WorkScopeTagExternalReference<'a>>,
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
        Option<StrongRef<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> WorkScopeTag<'a> {
    /// Create a new builder for this type
    pub fn new() -> WorkScopeTagBuilder<'a, work_scope_tag_state::Empty> {
        WorkScopeTagBuilder::new()
    }
}

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

impl<'a, S: work_scope_tag_state::State> WorkScopeTagBuilder<'a, S> {
    /// Set the `aliases` field (optional)
    pub fn aliases(mut self, value: impl Into<Option<Vec<CowStr<'a>>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `aliases` field to an Option value (optional)
    pub fn maybe_aliases(mut self, value: Option<Vec<CowStr<'a>>>) -> Self {
        self._fields.0 = value;
        self
    }
}

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

impl<'a, S: work_scope_tag_state::State> WorkScopeTagBuilder<'a, S> {
    /// Set the `description` field (optional)
    pub fn description(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `description` field to an Option value (optional)
    pub fn maybe_description(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<'a, S: work_scope_tag_state::State> WorkScopeTagBuilder<'a, S> {
    /// Set the `externalReference` field (optional)
    pub fn external_reference(
        mut self,
        value: impl Into<Option<WorkScopeTagExternalReference<'a>>>,
    ) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `externalReference` field to an Option value (optional)
    pub fn maybe_external_reference(
        mut self,
        value: Option<WorkScopeTagExternalReference<'a>>,
    ) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<'a, S> WorkScopeTagBuilder<'a, S>
where
    S: work_scope_tag_state::State,
    S::Key: work_scope_tag_state::IsUnset,
{
    /// Set the `key` field (required)
    pub fn key(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> WorkScopeTagBuilder<'a, work_scope_tag_state::SetKey<S>> {
        self._fields.4 = Option::Some(value.into());
        WorkScopeTagBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: work_scope_tag_state::State> WorkScopeTagBuilder<'a, S> {
    /// Set the `kind` field (optional)
    pub fn kind(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `kind` field to an Option value (optional)
    pub fn maybe_kind(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<'a, S> WorkScopeTagBuilder<'a, S>
where
    S: work_scope_tag_state::State,
    S::Label: work_scope_tag_state::IsUnset,
{
    /// Set the `label` field (required)
    pub fn label(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> WorkScopeTagBuilder<'a, work_scope_tag_state::SetLabel<S>> {
        self._fields.6 = Option::Some(value.into());
        WorkScopeTagBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: work_scope_tag_state::State> WorkScopeTagBuilder<'a, S> {
    /// Set the `parent` field (optional)
    pub fn parent(mut self, value: impl Into<Option<StrongRef<'a>>>) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `parent` field to an Option value (optional)
    pub fn maybe_parent(mut self, value: Option<StrongRef<'a>>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<'a, S> WorkScopeTagBuilder<'a, S>
where
    S: work_scope_tag_state::State,
    S::Key: work_scope_tag_state::IsSet,
    S::CreatedAt: work_scope_tag_state::IsSet,
    S::Label: work_scope_tag_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> WorkScopeTag<'a> {
        WorkScopeTag {
            aliases: self._fields.0,
            created_at: self._fields.1.unwrap(),
            description: self._fields.2,
            external_reference: self._fields.3,
            key: self._fields.4.unwrap(),
            kind: self._fields.5,
            label: self._fields.6.unwrap(),
            parent: self._fields.7,
            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>,
        >,
    ) -> WorkScopeTag<'a> {
        WorkScopeTag {
            aliases: self._fields.0,
            created_at: self._fields.1.unwrap(),
            description: self._fields.2,
            external_reference: self._fields.3,
            key: self._fields.4.unwrap(),
            kind: self._fields.5,
            label: self._fields.6.unwrap(),
            parent: self._fields.7,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_org_hypercerts_helper_workScopeTag() -> 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("org.hypercerts.helper.workScopeTag"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A reusable scope atom for work scope logic expressions. Scopes can represent topics, languages, domains, deliverables, methods, regions, tags, or other categorical labels.",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("createdAt"),
                                SmolStr::new_static("key"), SmolStr::new_static("label")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("aliases"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Optional array of alternative names or identifiers for this scope.",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        max_length: Some(200usize),
                                        ..Default::default()
                                    }),
                                    max_length: Some(50usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Client-declared timestamp when this record was originally created",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("description"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Optional longer description of this scope.",
                                        ),
                                    ),
                                    max_length: Some(10000usize),
                                    max_graphemes: Some(1000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("externalReference"),
                                LexObjectProperty::Union(LexRefUnion {
                                    description: Some(
                                        CowStr::new_static(
                                            "Optional external reference for this scope as a URI or blob.",
                                        ),
                                    ),
                                    refs: vec![
                                        CowStr::new_static("org.hypercerts.defs#uri"),
                                        CowStr::new_static("org.hypercerts.defs#smallBlob")
                                    ],
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("key"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Lowercase, hyphenated machine-readable key for this scope (e.g., 'ipfs', 'go-lang', 'filecoin').",
                                        ),
                                    ),
                                    max_length: Some(120usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("kind"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Category type of this scope. Recommended values: topic, language, domain, method, tag.",
                                        ),
                                    ),
                                    max_length: Some(50usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("label"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Human-readable label for this scope."),
                                    ),
                                    max_length: Some(200usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("parent"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("com.atproto.repo.strongRef"),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}