// @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, 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, UriValue};
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};
use crate::social_lexical::works::identifiers;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Identifier<S: BosStr = DefaultStr> {
    ///
    pub provider: IdentifierProvider<S>,
    ///
    pub provider_id: S,
    ///
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<UriValue<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 IdentifierProvider<S: BosStr = DefaultStr> {
    Tmdb,
    Imdb,
    Wikidata,
    Other(S),
}

impl<S: BosStr> IdentifierProvider<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Tmdb => "tmdb",
            Self::Imdb => "imdb",
            Self::Wikidata => "wikidata",
            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() {
            "tmdb" => Self::Tmdb,
            "imdb" => Self::Imdb,
            "wikidata" => Self::Wikidata,
            _ => Self::Other(s),
        }
    }
}

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

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

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

impl<S: BosStr> jacquard_common::IntoStatic for IdentifierProvider<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = IdentifierProvider<S::Output>;
    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()),
        }
    }
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "social.lexical.works.identifiers",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Identifiers<S: BosStr = DefaultStr> {
    pub identifiers: Vec<identifiers::Identifier<S>>,
    ///
    pub work: AtUri<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// 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<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Identifiers<S>,
}

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

impl<S: BosStr> LexiconSchema for Identifier<S> {
    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<S: BosStr> = IdentifiersGetRecordOutput<S>;
    type Err = RecordError;
}

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

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

/// Builder for constructing an instance of this type.
pub struct IdentifiersBuilder<St: identifiers_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (Option<Vec<identifiers::Identifier<S>>>, Option<AtUri<S>>),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

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

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

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