// @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, 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::collection::{Collection, RecordError};
use jacquard_common::types::string::{AtUri, Cid, Datetime};
use jacquard_common::types::uri::{RecordUri, UriError};
use jacquard_common::types::value::Data;
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};

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "diy.razorgirl.winter.wikiLink",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct WikiLink<S: BosStr = DefaultStr> {
    ///Why this link exists
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context: Option<S>,
    pub created_at: Datetime,
    pub link_type: WikiLinkLinkType<S>,
    pub source: AtUri<S>,
    ///Section heading slug in source
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_anchor: Option<S>,
    pub target: AtUri<S>,
    ///Section heading slug in target
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_anchor: Option<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 WikiLinkLinkType<S: BosStr = DefaultStr> {
    RelatedTo,
    DependsOn,
    Extends,
    Contradicts,
    IsExampleOf,
    Supersedes,
    References,
    Defines,
    IsPartOf,
    Other(S),
}

impl<S: BosStr> WikiLinkLinkType<S> {
    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(),
        }
    }
    /// Construct from a string-like value, matching known values.
    pub fn from_value(s: S) -> Self {
        match s.as_ref() {
            "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(s),
        }
    }
}

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

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

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

impl<S: BosStr> jacquard_common::IntoStatic for WikiLinkLinkType<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = WikiLinkLinkType<S::Output>;
    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<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: WikiLink<S>,
}

impl<S: BosStr> WikiLink<S> {
    pub fn uri(uri: S) -> Result<RecordUri<S, WikiLinkRecord>, UriError> {
        RecordUri::try_from_uri(AtUri::new(uri)?)
    }
}

/// 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<S: BosStr> = WikiLinkGetRecordOutput<S>;
    type Err = RecordError;
}

impl<S: BosStr> From<WikiLinkGetRecordOutput<S>> for WikiLink<S> {
    fn from(output: WikiLinkGetRecordOutput<S>) -> Self {
        output.value
    }
}

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

/// Builder for constructing an instance of this type.
pub struct WikiLinkBuilder<St: wiki_link_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<S>,
        Option<Datetime>,
        Option<WikiLinkLinkType<S>>,
        Option<AtUri<S>>,
        Option<S>,
        Option<AtUri<S>>,
        Option<S>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

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

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

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

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

impl<St: wiki_link_state::State, S: BosStr> WikiLinkBuilder<St, S> {
    /// Set the `sourceAnchor` field (optional)
    pub fn source_anchor(mut self, value: impl Into<Option<S>>) -> 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<S>) -> Self {
        self._fields.4 = value;
        self
    }
}

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

impl<St: wiki_link_state::State, S: BosStr> WikiLinkBuilder<St, S> {
    /// Set the `targetAnchor` field (optional)
    pub fn target_anchor(mut self, value: impl Into<Option<S>>) -> 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<S>) -> Self {
        self._fields.6 = value;
        self
    }
}

impl<St, S: BosStr> WikiLinkBuilder<St, S>
where
    St: wiki_link_state::State,
    St::CreatedAt: wiki_link_state::IsSet,
    St::LinkType: wiki_link_state::IsSet,
    St::Source: wiki_link_state::IsSet,
    St::Target: wiki_link_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> WikiLink<S> {
        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<SmolStr, Data<S>>) -> WikiLink<S> {
        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()
    }
}