// @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, 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};
use crate::at_margin::preferences;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct LabelPreference<S: BosStr = DefaultStr> {
    ///The label identifier (e.g. sexual, violence, spam).
    pub label: S,
    ///DID of the labeler service.
    pub labeler_did: S,
    ///How to handle content with this label: hide, warn, or ignore.
    pub visibility: LabelPreferenceVisibility<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

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

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum LabelPreferenceVisibility<S: BosStr = DefaultStr> {
    Hide,
    Warn,
    Ignore,
    Other(S),
}

impl<S: BosStr> LabelPreferenceVisibility<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Hide => "hide",
            Self::Warn => "warn",
            Self::Ignore => "ignore",
            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() {
            "hide" => Self::Hide,
            "warn" => Self::Warn,
            "ignore" => Self::Ignore,
            _ => Self::Other(s),
        }
    }
}

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

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

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

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


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct LabelerSubscription<S: BosStr = DefaultStr> {
    ///DID of the labeler service.
    pub did: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// User preferences for the Margin application.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "at.margin.preferences",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Preferences<S: BosStr = DefaultStr> {
    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")]
    pub external_link_skipped_hostnames: Option<Vec<S>>,
    ///Per-label visibility preferences for subscribed labelers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label_preferences: Option<Vec<preferences::LabelPreference<S>>>,
    ///List of labeler services the user subscribes to for content moderation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subscribed_labelers: Option<Vec<preferences::LabelerSubscription<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 PreferencesGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Preferences<S>,
}

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

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

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

impl<S: BosStr> Collection for Preferences<S> {
    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<S: BosStr> LexiconSchema for Preferences<S> {
    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<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>;
    }
    /// 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<St: preferences_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Datetime>,
        Option<bool>,
        Option<Vec<S>>,
        Option<Vec<preferences::LabelPreference<S>>>,
        Option<Vec<preferences::LabelerSubscription<S>>>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

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

impl<St: preferences_state::State, S: BosStr> PreferencesBuilder<St, 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<St: preferences_state::State, S: BosStr> PreferencesBuilder<St, S> {
    /// Set the `externalLinkSkippedHostnames` field (optional)
    pub fn external_link_skipped_hostnames(
        mut self,
        value: impl Into<Option<Vec<S>>>,
    ) -> 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<S>>,
    ) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<St: preferences_state::State, S: BosStr> PreferencesBuilder<St, S> {
    /// Set the `labelPreferences` field (optional)
    pub fn label_preferences(
        mut self,
        value: impl Into<Option<Vec<preferences::LabelPreference<S>>>>,
    ) -> 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<S>>>,
    ) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St: preferences_state::State, S: BosStr> PreferencesBuilder<St, S> {
    /// Set the `subscribedLabelers` field (optional)
    pub fn subscribed_labelers(
        mut self,
        value: impl Into<Option<Vec<preferences::LabelerSubscription<S>>>>,
    ) -> 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<S>>>,
    ) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St, S: BosStr> PreferencesBuilder<St, S>
where
    St: preferences_state::State,
    St::CreatedAt: preferences_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Preferences<S> {
        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<SmolStr, Data<S>>,
    ) -> Preferences<S> {
        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),
        }
    }
}