// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: at.margin.preferences
//
// 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};
use crate::at_margin::preferences;

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct LabelPreference<'a> {
    ///The label identifier (e.g. sexual, violence, spam).
    #[serde(borrow)]
    pub label: CowStr<'a>,
    ///DID of the labeler service.
    #[serde(borrow)]
    pub labeler_did: CowStr<'a>,
    ///How to handle content with this label: hide, warn, or ignore.
    #[serde(borrow)]
    pub visibility: LabelPreferenceVisibility<'a>,
}

/// How to handle content with this label: hide, warn, or ignore.

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum LabelPreferenceVisibility<'a> {
    Hide,
    Warn,
    Ignore,
    Other(CowStr<'a>),
}

impl<'a> LabelPreferenceVisibility<'a> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Hide => "hide",
            Self::Warn => "warn",
            Self::Ignore => "ignore",
            Self::Other(s) => s.as_ref(),
        }
    }
}

impl<'a> From<&'a str> for LabelPreferenceVisibility<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "hide" => Self::Hide,
            "warn" => Self::Warn,
            "ignore" => Self::Ignore,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for LabelPreferenceVisibility<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "hide" => Self::Hide,
            "warn" => Self::Warn,
            "ignore" => Self::Ignore,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

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

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

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

impl jacquard_common::IntoStatic for LabelPreferenceVisibility<'_> {
    type Output = LabelPreferenceVisibility<'static>;
    fn into_static(self) -> Self::Output {
        match self {
            LabelPreferenceVisibility::Hide => LabelPreferenceVisibility::Hide,
            LabelPreferenceVisibility::Warn => LabelPreferenceVisibility::Warn,
            LabelPreferenceVisibility::Ignore => LabelPreferenceVisibility::Ignore,
            LabelPreferenceVisibility::Other(v) => {
                LabelPreferenceVisibility::Other(v.into_static())
            }
        }
    }
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct LabelerSubscription<'a> {
    ///DID of the labeler service.
    #[serde(borrow)]
    pub did: CowStr<'a>,
}

/// User preferences for the Margin application.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Preferences<'a> {
    pub created_at: Datetime,
    ///If true, do not show the confirmation modal when opening external links.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub disable_external_link_warning: Option<bool>,
    ///List of hostnames to skip the external link warning modal for.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub external_link_skipped_hostnames: Option<Vec<CowStr<'a>>>,
    ///Per-label visibility preferences for subscribed labelers.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub label_preferences: Option<Vec<preferences::LabelPreference<'a>>>,
    ///List of labeler services the user subscribes to for content moderation.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub subscribed_labelers: Option<Vec<preferences::LabelerSubscription<'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 PreferencesGetRecordOutput<'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: Preferences<'a>,
}

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

impl<'a> LexiconSchema for LabelPreference<'a> {
    fn nsid() -> &'static str {
        "at.margin.preferences"
    }
    fn def_name() -> &'static str {
        "labelPreference"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_margin_preferences()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

impl<'a> LexiconSchema for LabelerSubscription<'a> {
    fn nsid() -> &'static str {
        "at.margin.preferences"
    }
    fn def_name() -> &'static str {
        "labelerSubscription"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_margin_preferences()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

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

#[derive(Debug, Serialize, Deserialize)]
pub struct PreferencesRecord;
impl XrpcResp for PreferencesRecord {
    const NSID: &'static str = "at.margin.preferences";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = PreferencesGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Preferences<'_> {
    const NSID: &'static str = "at.margin.preferences";
    type Record = PreferencesRecord;
}

impl Collection for PreferencesRecord {
    const NSID: &'static str = "at.margin.preferences";
    type Record = PreferencesRecord;
}

impl<'a> LexiconSchema for Preferences<'a> {
    fn nsid() -> &'static str {
        "at.margin.preferences"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_margin_preferences()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.external_link_skipped_hostnames {
            #[allow(unused_comparisons)]
            if value.len() > 100usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("external_link_skipped_hostnames"),
                    max: 100usize,
                    actual: value.len(),
                });
            }
        }
        if let Some(ref value) = self.label_preferences {
            #[allow(unused_comparisons)]
            if value.len() > 500usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("label_preferences"),
                    max: 500usize,
                    actual: value.len(),
                });
            }
        }
        if let Some(ref value) = self.subscribed_labelers {
            #[allow(unused_comparisons)]
            if value.len() > 50usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("subscribed_labelers"),
                    max: 50usize,
                    actual: value.len(),
                });
            }
        }
        Ok(())
    }
}

fn lexicon_doc_at_margin_preferences() -> 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("at.margin.preferences"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("labelPreference"),
                LexUserType::Object(LexObject {
                    required: Some(
                        vec![
                            SmolStr::new_static("labelerDid"),
                            SmolStr::new_static("label"),
                            SmolStr::new_static("visibility")
                        ],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("label"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "The label identifier (e.g. sexual, violence, spam).",
                                    ),
                                ),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("labelerDid"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("DID of the labeler service."),
                                ),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("visibility"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "How to handle content with this label: hide, warn, or ignore.",
                                    ),
                                ),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("labelerSubscription"),
                LexUserType::Object(LexObject {
                    required: Some(vec![SmolStr::new_static("did")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("did"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("DID of the labeler service."),
                                ),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "User preferences for the Margin application.",
                        ),
                    ),
                    key: Some(CowStr::new_static("literal:self")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(vec![SmolStr::new_static("createdAt")]),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("disableExternalLinkWarning"),
                                LexObjectProperty::Boolean(LexBoolean {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("externalLinkSkippedHostnames"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "List of hostnames to skip the external link warning modal for.",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        max_length: Some(255usize),
                                        ..Default::default()
                                    }),
                                    max_length: Some(100usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("labelPreferences"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Per-label visibility preferences for subscribed labelers.",
                                        ),
                                    ),
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#labelPreference"),
                                        ..Default::default()
                                    }),
                                    max_length: Some(500usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("subscribedLabelers"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "List of labeler services the user subscribes to for content moderation.",
                                        ),
                                    ),
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#labelerSubscription"),
                                        ..Default::default()
                                    }),
                                    max_length: Some(50usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod preferences_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;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedAt = 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>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `created_at` field
        pub struct created_at(());
    }
}

/// Builder for constructing an instance of this type
pub struct PreferencesBuilder<'a, S: preferences_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Datetime>,
        Option<bool>,
        Option<Vec<CowStr<'a>>>,
        Option<Vec<preferences::LabelPreference<'a>>>,
        Option<Vec<preferences::LabelerSubscription<'a>>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Preferences<'a> {
    /// Create a new builder for this type
    pub fn new() -> PreferencesBuilder<'a, preferences_state::Empty> {
        PreferencesBuilder::new()
    }
}

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

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

impl<'a, S: preferences_state::State> PreferencesBuilder<'a, S> {
    /// Set the `disableExternalLinkWarning` field (optional)
    pub fn disable_external_link_warning(
        mut self,
        value: impl Into<Option<bool>>,
    ) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `disableExternalLinkWarning` field to an Option value (optional)
    pub fn maybe_disable_external_link_warning(mut self, value: Option<bool>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<'a, S: preferences_state::State> PreferencesBuilder<'a, S> {
    /// Set the `externalLinkSkippedHostnames` field (optional)
    pub fn external_link_skipped_hostnames(
        mut self,
        value: impl Into<Option<Vec<CowStr<'a>>>>,
    ) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `externalLinkSkippedHostnames` field to an Option value (optional)
    pub fn maybe_external_link_skipped_hostnames(
        mut self,
        value: Option<Vec<CowStr<'a>>>,
    ) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<'a, S: preferences_state::State> PreferencesBuilder<'a, S> {
    /// Set the `labelPreferences` field (optional)
    pub fn label_preferences(
        mut self,
        value: impl Into<Option<Vec<preferences::LabelPreference<'a>>>>,
    ) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `labelPreferences` field to an Option value (optional)
    pub fn maybe_label_preferences(
        mut self,
        value: Option<Vec<preferences::LabelPreference<'a>>>,
    ) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<'a, S: preferences_state::State> PreferencesBuilder<'a, S> {
    /// Set the `subscribedLabelers` field (optional)
    pub fn subscribed_labelers(
        mut self,
        value: impl Into<Option<Vec<preferences::LabelerSubscription<'a>>>>,
    ) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `subscribedLabelers` field to an Option value (optional)
    pub fn maybe_subscribed_labelers(
        mut self,
        value: Option<Vec<preferences::LabelerSubscription<'a>>>,
    ) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<'a, S> PreferencesBuilder<'a, S>
where
    S: preferences_state::State,
    S::CreatedAt: preferences_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Preferences<'a> {
        Preferences {
            created_at: self._fields.0.unwrap(),
            disable_external_link_warning: self._fields.1,
            external_link_skipped_hostnames: self._fields.2,
            label_preferences: self._fields.3,
            subscribed_labelers: self._fields.4,
            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>,
        >,
    ) -> Preferences<'a> {
        Preferences {
            created_at: self._fields.0.unwrap(),
            disable_external_link_warning: self._fields.1,
            external_link_skipped_hostnames: self._fields.2,
            label_preferences: self._fields.3,
            subscribed_labelers: self._fields.4,
            extra_data: Some(extra_data),
        }
    }
}