// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: social.lexical.works.identifiers
//
// 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, UriValue};
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::social_lexical::works::identifiers;

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct Identifier<'a> {
    ///
    #[serde(borrow)]
    pub provider: IdentifierProvider<'a>,
    ///
    #[serde(borrow)]
    pub provider_id: CowStr<'a>,
    ///
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub url: Option<UriValue<'a>>,
}

///

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum IdentifierProvider<'a> {
    Tmdb,
    Imdb,
    Wikidata,
    Other(CowStr<'a>),
}

impl<'a> IdentifierProvider<'a> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Tmdb => "tmdb",
            Self::Imdb => "imdb",
            Self::Wikidata => "wikidata",
            Self::Other(s) => s.as_ref(),
        }
    }
}

impl<'a> From<&'a str> for IdentifierProvider<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "tmdb" => Self::Tmdb,
            "imdb" => Self::Imdb,
            "wikidata" => Self::Wikidata,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for IdentifierProvider<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "tmdb" => Self::Tmdb,
            "imdb" => Self::Imdb,
            "wikidata" => Self::Wikidata,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

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

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

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

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


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Identifiers<'a> {
    #[serde(borrow)]
    pub identifiers: Vec<identifiers::Identifier<'a>>,
    ///
    #[serde(borrow)]
    pub work: AtUri<'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 IdentifiersGetRecordOutput<'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: Identifiers<'a>,
}

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

impl<'a> LexiconSchema for Identifier<'a> {
    fn nsid() -> &'static str {
        "social.lexical.works.identifiers"
    }
    fn def_name() -> &'static str {
        "identifier"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_social_lexical_works_identifiers()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

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

#[derive(Debug, Serialize, Deserialize)]
pub struct IdentifiersRecord;
impl XrpcResp for IdentifiersRecord {
    const NSID: &'static str = "social.lexical.works.identifiers";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = IdentifiersGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Identifiers<'_> {
    const NSID: &'static str = "social.lexical.works.identifiers";
    type Record = IdentifiersRecord;
}

impl Collection for IdentifiersRecord {
    const NSID: &'static str = "social.lexical.works.identifiers";
    type Record = IdentifiersRecord;
}

impl<'a> LexiconSchema for Identifiers<'a> {
    fn nsid() -> &'static str {
        "social.lexical.works.identifiers"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_social_lexical_works_identifiers()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.identifiers;
            #[allow(unused_comparisons)]
            if value.len() < 1usize {
                return Err(ConstraintError::MinLength {
                    path: ValidationPath::from_field("identifiers"),
                    min: 1usize,
                    actual: value.len(),
                });
            }
        }
        Ok(())
    }
}

fn lexicon_doc_social_lexical_works_identifiers() -> 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("social.lexical.works.identifiers"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("identifier"),
                LexUserType::Object(LexObject {
                    required: Some(
                        vec![
                            SmolStr::new_static("provider"),
                            SmolStr::new_static("providerId")
                        ],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("provider"),
                            LexObjectProperty::String(LexString {
                                description: Some(CowStr::new_static("")),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("providerId"),
                            LexObjectProperty::String(LexString {
                                description: Some(CowStr::new_static("")),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("url"),
                            LexObjectProperty::String(LexString {
                                description: Some(CowStr::new_static("")),
                                format: Some(LexStringFormat::Uri),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    key: Some(CowStr::new_static("any")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("work"),
                                SmolStr::new_static("identifiers")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("identifiers"),
                                LexObjectProperty::Array(LexArray {
                                    items: LexArrayItem::Union(LexRefUnion {
                                        refs: vec![CowStr::new_static("#identifier")],
                                        closed: Some(false),
                                        ..Default::default()
                                    }),
                                    min_length: Some(1usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("work"),
                                LexObjectProperty::String(LexString {
                                    description: Some(CowStr::new_static("")),
                                    format: Some(LexStringFormat::AtUri),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod identifiers_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 Work;
        type Identifiers;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Work = Unset;
        type Identifiers = Unset;
    }
    ///State transition - sets the `work` field to Set
    pub struct SetWork<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetWork<S> {}
    impl<S: State> State for SetWork<S> {
        type Work = Set<members::work>;
        type Identifiers = S::Identifiers;
    }
    ///State transition - sets the `identifiers` field to Set
    pub struct SetIdentifiers<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetIdentifiers<S> {}
    impl<S: State> State for SetIdentifiers<S> {
        type Work = S::Work;
        type Identifiers = Set<members::identifiers>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `work` field
        pub struct work(());
        ///Marker type for the `identifiers` field
        pub struct identifiers(());
    }
}

/// Builder for constructing an instance of this type
pub struct IdentifiersBuilder<'a, S: identifiers_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (Option<Vec<identifiers::Identifier<'a>>>, Option<AtUri<'a>>),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Identifiers<'a> {
    /// Create a new builder for this type
    pub fn new() -> IdentifiersBuilder<'a, identifiers_state::Empty> {
        IdentifiersBuilder::new()
    }
}

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

impl<'a, S> IdentifiersBuilder<'a, S>
where
    S: identifiers_state::State,
    S::Identifiers: identifiers_state::IsUnset,
{
    /// Set the `identifiers` field (required)
    pub fn identifiers(
        mut self,
        value: impl Into<Vec<identifiers::Identifier<'a>>>,
    ) -> IdentifiersBuilder<'a, identifiers_state::SetIdentifiers<S>> {
        self._fields.0 = Option::Some(value.into());
        IdentifiersBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> IdentifiersBuilder<'a, S>
where
    S: identifiers_state::State,
    S::Work: identifiers_state::IsUnset,
{
    /// Set the `work` field (required)
    pub fn work(
        mut self,
        value: impl Into<AtUri<'a>>,
    ) -> IdentifiersBuilder<'a, identifiers_state::SetWork<S>> {
        self._fields.1 = Option::Some(value.into());
        IdentifiersBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> IdentifiersBuilder<'a, S>
where
    S: identifiers_state::State,
    S::Work: identifiers_state::IsSet,
    S::Identifiers: identifiers_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Identifiers<'a> {
        Identifiers {
            identifiers: self._fields.0.unwrap(),
            work: 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>,
        >,
    ) -> Identifiers<'a> {
        Identifiers {
            identifiers: self._fields.0.unwrap(),
            work: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}