// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: diy.razorgirl.winter.wikiLink
//
// 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};
use jacquard_lexicon::lexicon::LexiconDoc;
use jacquard_lexicon::schema::LexiconSchema;

#[allow(unused_imports)]
use jacquard_lexicon::validation::{ConstraintError, ValidationPath};
use serde::{Serialize, Deserialize};

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct WikiLink<'a> {
    ///Why this link exists
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub context: Option<CowStr<'a>>,
    pub created_at: Datetime,
    #[serde(borrow)]
    pub link_type: WikiLinkLinkType<'a>,
    #[serde(borrow)]
    pub source: AtUri<'a>,
    ///Section heading slug in source
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub source_anchor: Option<CowStr<'a>>,
    #[serde(borrow)]
    pub target: AtUri<'a>,
    ///Section heading slug in target
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub target_anchor: Option<CowStr<'a>>,
}


#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum WikiLinkLinkType<'a> {
    RelatedTo,
    DependsOn,
    Extends,
    Contradicts,
    IsExampleOf,
    Supersedes,
    References,
    Defines,
    IsPartOf,
    Other(CowStr<'a>),
}

impl<'a> WikiLinkLinkType<'a> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::RelatedTo => "related-to",
            Self::DependsOn => "depends-on",
            Self::Extends => "extends",
            Self::Contradicts => "contradicts",
            Self::IsExampleOf => "is-example-of",
            Self::Supersedes => "supersedes",
            Self::References => "references",
            Self::Defines => "defines",
            Self::IsPartOf => "is-part-of",
            Self::Other(s) => s.as_ref(),
        }
    }
}

impl<'a> From<&'a str> for WikiLinkLinkType<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "related-to" => Self::RelatedTo,
            "depends-on" => Self::DependsOn,
            "extends" => Self::Extends,
            "contradicts" => Self::Contradicts,
            "is-example-of" => Self::IsExampleOf,
            "supersedes" => Self::Supersedes,
            "references" => Self::References,
            "defines" => Self::Defines,
            "is-part-of" => Self::IsPartOf,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for WikiLinkLinkType<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "related-to" => Self::RelatedTo,
            "depends-on" => Self::DependsOn,
            "extends" => Self::Extends,
            "contradicts" => Self::Contradicts,
            "is-example-of" => Self::IsExampleOf,
            "supersedes" => Self::Supersedes,
            "references" => Self::References,
            "defines" => Self::Defines,
            "is-part-of" => Self::IsPartOf,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

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

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

impl<'a> serde::Serialize for WikiLinkLinkType<'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 WikiLinkLinkType<'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 WikiLinkLinkType<'a> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl jacquard_common::IntoStatic for WikiLinkLinkType<'_> {
    type Output = WikiLinkLinkType<'static>;
    fn into_static(self) -> Self::Output {
        match self {
            WikiLinkLinkType::RelatedTo => WikiLinkLinkType::RelatedTo,
            WikiLinkLinkType::DependsOn => WikiLinkLinkType::DependsOn,
            WikiLinkLinkType::Extends => WikiLinkLinkType::Extends,
            WikiLinkLinkType::Contradicts => WikiLinkLinkType::Contradicts,
            WikiLinkLinkType::IsExampleOf => WikiLinkLinkType::IsExampleOf,
            WikiLinkLinkType::Supersedes => WikiLinkLinkType::Supersedes,
            WikiLinkLinkType::References => WikiLinkLinkType::References,
            WikiLinkLinkType::Defines => WikiLinkLinkType::Defines,
            WikiLinkLinkType::IsPartOf => WikiLinkLinkType::IsPartOf,
            WikiLinkLinkType::Other(v) => WikiLinkLinkType::Other(v.into_static()),
        }
    }
}

/// 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 WikiLinkGetRecordOutput<'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: WikiLink<'a>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct WikiLinkRecord;
impl XrpcResp for WikiLinkRecord {
    const NSID: &'static str = "diy.razorgirl.winter.wikiLink";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = WikiLinkGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for WikiLink<'_> {
    const NSID: &'static str = "diy.razorgirl.winter.wikiLink";
    type Record = WikiLinkRecord;
}

impl Collection for WikiLinkRecord {
    const NSID: &'static str = "diy.razorgirl.winter.wikiLink";
    type Record = WikiLinkRecord;
}

impl<'a> LexiconSchema for WikiLink<'a> {
    fn nsid() -> &'static str {
        "diy.razorgirl.winter.wikiLink"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_diy_razorgirl_winter_wikiLink()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.context {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 512usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("context"),
                    max: 512usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod wiki_link_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 Target;
        type LinkType;
        type Source;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedAt = Unset;
        type Target = Unset;
        type LinkType = Unset;
        type Source = Unset;
    }
    ///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 CreatedAt = Set<members::created_at>;
        type Target = S::Target;
        type LinkType = S::LinkType;
        type Source = S::Source;
    }
    ///State transition - sets the `target` field to Set
    pub struct SetTarget<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetTarget<S> {}
    impl<S: State> State for SetTarget<S> {
        type CreatedAt = S::CreatedAt;
        type Target = Set<members::target>;
        type LinkType = S::LinkType;
        type Source = S::Source;
    }
    ///State transition - sets the `link_type` field to Set
    pub struct SetLinkType<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetLinkType<S> {}
    impl<S: State> State for SetLinkType<S> {
        type CreatedAt = S::CreatedAt;
        type Target = S::Target;
        type LinkType = Set<members::link_type>;
        type Source = S::Source;
    }
    ///State transition - sets the `source` field to Set
    pub struct SetSource<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetSource<S> {}
    impl<S: State> State for SetSource<S> {
        type CreatedAt = S::CreatedAt;
        type Target = S::Target;
        type LinkType = S::LinkType;
        type Source = Set<members::source>;
    }
    /// 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 `target` field
        pub struct target(());
        ///Marker type for the `link_type` field
        pub struct link_type(());
        ///Marker type for the `source` field
        pub struct source(());
    }
}

/// Builder for constructing an instance of this type
pub struct WikiLinkBuilder<'a, S: wiki_link_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<CowStr<'a>>,
        Option<Datetime>,
        Option<WikiLinkLinkType<'a>>,
        Option<AtUri<'a>>,
        Option<CowStr<'a>>,
        Option<AtUri<'a>>,
        Option<CowStr<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> WikiLink<'a> {
    /// Create a new builder for this type
    pub fn new() -> WikiLinkBuilder<'a, wiki_link_state::Empty> {
        WikiLinkBuilder::new()
    }
}

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

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

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

impl<'a, S> WikiLinkBuilder<'a, S>
where
    S: wiki_link_state::State,
    S::LinkType: wiki_link_state::IsUnset,
{
    /// Set the `linkType` field (required)
    pub fn link_type(
        mut self,
        value: impl Into<WikiLinkLinkType<'a>>,
    ) -> WikiLinkBuilder<'a, wiki_link_state::SetLinkType<S>> {
        self._fields.2 = Option::Some(value.into());
        WikiLinkBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> WikiLinkBuilder<'a, S>
where
    S: wiki_link_state::State,
    S::Source: wiki_link_state::IsUnset,
{
    /// Set the `source` field (required)
    pub fn source(
        mut self,
        value: impl Into<AtUri<'a>>,
    ) -> WikiLinkBuilder<'a, wiki_link_state::SetSource<S>> {
        self._fields.3 = Option::Some(value.into());
        WikiLinkBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: wiki_link_state::State> WikiLinkBuilder<'a, S> {
    /// Set the `sourceAnchor` field (optional)
    pub fn source_anchor(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `sourceAnchor` field to an Option value (optional)
    pub fn maybe_source_anchor(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<'a, S> WikiLinkBuilder<'a, S>
where
    S: wiki_link_state::State,
    S::Target: wiki_link_state::IsUnset,
{
    /// Set the `target` field (required)
    pub fn target(
        mut self,
        value: impl Into<AtUri<'a>>,
    ) -> WikiLinkBuilder<'a, wiki_link_state::SetTarget<S>> {
        self._fields.5 = Option::Some(value.into());
        WikiLinkBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: wiki_link_state::State> WikiLinkBuilder<'a, S> {
    /// Set the `targetAnchor` field (optional)
    pub fn target_anchor(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.6 = value.into();
        self
    }
    /// Set the `targetAnchor` field to an Option value (optional)
    pub fn maybe_target_anchor(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.6 = value;
        self
    }
}

impl<'a, S> WikiLinkBuilder<'a, S>
where
    S: wiki_link_state::State,
    S::CreatedAt: wiki_link_state::IsSet,
    S::Target: wiki_link_state::IsSet,
    S::LinkType: wiki_link_state::IsSet,
    S::Source: wiki_link_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> WikiLink<'a> {
        WikiLink {
            context: self._fields.0,
            created_at: self._fields.1.unwrap(),
            link_type: self._fields.2.unwrap(),
            source: self._fields.3.unwrap(),
            source_anchor: self._fields.4,
            target: self._fields.5.unwrap(),
            target_anchor: self._fields.6,
            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>,
        >,
    ) -> WikiLink<'a> {
        WikiLink {
            context: self._fields.0,
            created_at: self._fields.1.unwrap(),
            link_type: self._fields.2.unwrap(),
            source: self._fields.3.unwrap(),
            source_anchor: self._fields.4,
            target: self._fields.5.unwrap(),
            target_anchor: self._fields.6,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_diy_razorgirl_winter_wikiLink() -> 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("diy.razorgirl.winter.wikiLink"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("source"),
                                SmolStr::new_static("target"),
                                SmolStr::new_static("linkType"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("context"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Why this link exists"),
                                    ),
                                    max_length: Some(512usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("linkType"),
                                LexObjectProperty::String(LexString {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("source"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::AtUri),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("sourceAnchor"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Section heading slug in source"),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("target"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::AtUri),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("targetAnchor"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Section heading slug in target"),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}