// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: dev.keytrace.userPublicKey
//
// 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};
/// A user-published public key.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "dev.keytrace.userPublicKey",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct UserPublicKey<S: BosStr = DefaultStr> {
    ///Optional comment or description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub comment: Option<S>,
    ///Datetime when this key was created (ISO 8601).
    pub created_at: Datetime,
    ///Datetime when this key expires (ISO 8601).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<Datetime>,
    ///Key fingerprint.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fingerprint: Option<S>,
    ///Format of the public key.
    pub key_type: UserPublicKeyKeyType<S>,
    ///Human-readable label for this key (e.g., 'work laptop', 'signing key').
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<S>,
    ///Full public key in standard text armored format.
    pub public_key_armored: S,
    ///Datetime when this key was retracted. Present only if the key has been retracted (ISO 8601).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retracted_at: Option<Datetime>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// Format of the public key.

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum UserPublicKeyKeyType<S: BosStr = DefaultStr> {
    Pgp,
    SshEd25519,
    SshEcdsa,
    Other(S),
}

impl<S: BosStr> UserPublicKeyKeyType<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Pgp => "pgp",
            Self::SshEd25519 => "ssh-ed25519",
            Self::SshEcdsa => "ssh-ecdsa",
            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() {
            "pgp" => Self::Pgp,
            "ssh-ed25519" => Self::SshEd25519,
            "ssh-ecdsa" => Self::SshEcdsa,
            _ => Self::Other(s),
        }
    }
}

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

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

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

impl<S: BosStr> jacquard_common::IntoStatic for UserPublicKeyKeyType<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = UserPublicKeyKeyType<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            UserPublicKeyKeyType::Pgp => UserPublicKeyKeyType::Pgp,
            UserPublicKeyKeyType::SshEd25519 => UserPublicKeyKeyType::SshEd25519,
            UserPublicKeyKeyType::SshEcdsa => UserPublicKeyKeyType::SshEcdsa,
            UserPublicKeyKeyType::Other(v) => {
                UserPublicKeyKeyType::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 UserPublicKeyGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: UserPublicKey<S>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct UserPublicKeyRecord;
impl XrpcResp for UserPublicKeyRecord {
    const NSID: &'static str = "dev.keytrace.userPublicKey";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = UserPublicKeyGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for UserPublicKey<S> {
    const NSID: &'static str = "dev.keytrace.userPublicKey";
    type Record = UserPublicKeyRecord;
}

impl Collection for UserPublicKeyRecord {
    const NSID: &'static str = "dev.keytrace.userPublicKey";
    type Record = UserPublicKeyRecord;
}

impl<S: BosStr> LexiconSchema for UserPublicKey<S> {
    fn nsid() -> &'static str {
        "dev.keytrace.userPublicKey"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_dev_keytrace_userPublicKey()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.comment {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 512usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("comment"),
                        max: 512usize,
                        actual: count,
                    });
                }
            }
        }
        if let Some(ref value) = self.fingerprint {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 256usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("fingerprint"),
                        max: 256usize,
                        actual: count,
                    });
                }
            }
        }
        if let Some(ref value) = self.label {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 128usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("label"),
                        max: 128usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let value = &self.public_key_armored;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 16384usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("public_key_armored"),
                    max: 16384usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.public_key_armored;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 16384usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("public_key_armored"),
                        max: 16384usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

pub mod user_public_key_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 KeyType;
        type PublicKeyArmored;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedAt = Unset;
        type KeyType = Unset;
        type PublicKeyArmored = 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 KeyType = St::KeyType;
        type PublicKeyArmored = St::PublicKeyArmored;
    }
    ///State transition - sets the `key_type` field to Set
    pub struct SetKeyType<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetKeyType<St> {}
    impl<St: State> State for SetKeyType<St> {
        type CreatedAt = St::CreatedAt;
        type KeyType = Set<members::key_type>;
        type PublicKeyArmored = St::PublicKeyArmored;
    }
    ///State transition - sets the `public_key_armored` field to Set
    pub struct SetPublicKeyArmored<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetPublicKeyArmored<St> {}
    impl<St: State> State for SetPublicKeyArmored<St> {
        type CreatedAt = St::CreatedAt;
        type KeyType = St::KeyType;
        type PublicKeyArmored = Set<members::public_key_armored>;
    }
    /// 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 `key_type` field
        pub struct key_type(());
        ///Marker type for the `public_key_armored` field
        pub struct public_key_armored(());
    }
}

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

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

impl<S: BosStr> UserPublicKey<S> {
    /// Create a new builder for this type
    pub fn builder() -> UserPublicKeyBuilder<user_public_key_state::Empty, S> {
        UserPublicKeyBuilder::builder()
    }
}

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

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

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

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

impl<St: user_public_key_state::State, S: BosStr> UserPublicKeyBuilder<St, S> {
    /// Set the `expiresAt` field (optional)
    pub fn expires_at(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `expiresAt` field to an Option value (optional)
    pub fn maybe_expires_at(mut self, value: Option<Datetime>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<St: user_public_key_state::State, S: BosStr> UserPublicKeyBuilder<St, S> {
    /// Set the `fingerprint` field (optional)
    pub fn fingerprint(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `fingerprint` field to an Option value (optional)
    pub fn maybe_fingerprint(mut self, value: Option<S>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St, S: BosStr> UserPublicKeyBuilder<St, S>
where
    St: user_public_key_state::State,
    St::KeyType: user_public_key_state::IsUnset,
{
    /// Set the `keyType` field (required)
    pub fn key_type(
        mut self,
        value: impl Into<UserPublicKeyKeyType<S>>,
    ) -> UserPublicKeyBuilder<user_public_key_state::SetKeyType<St>, S> {
        self._fields.4 = Option::Some(value.into());
        UserPublicKeyBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: user_public_key_state::State, S: BosStr> UserPublicKeyBuilder<St, S> {
    /// Set the `label` field (optional)
    pub fn label(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `label` field to an Option value (optional)
    pub fn maybe_label(mut self, value: Option<S>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<St, S: BosStr> UserPublicKeyBuilder<St, S>
where
    St: user_public_key_state::State,
    St::PublicKeyArmored: user_public_key_state::IsUnset,
{
    /// Set the `publicKeyArmored` field (required)
    pub fn public_key_armored(
        mut self,
        value: impl Into<S>,
    ) -> UserPublicKeyBuilder<user_public_key_state::SetPublicKeyArmored<St>, S> {
        self._fields.6 = Option::Some(value.into());
        UserPublicKeyBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: user_public_key_state::State, S: BosStr> UserPublicKeyBuilder<St, S> {
    /// Set the `retractedAt` field (optional)
    pub fn retracted_at(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `retractedAt` field to an Option value (optional)
    pub fn maybe_retracted_at(mut self, value: Option<Datetime>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<St, S: BosStr> UserPublicKeyBuilder<St, S>
where
    St: user_public_key_state::State,
    St::CreatedAt: user_public_key_state::IsSet,
    St::KeyType: user_public_key_state::IsSet,
    St::PublicKeyArmored: user_public_key_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> UserPublicKey<S> {
        UserPublicKey {
            comment: self._fields.0,
            created_at: self._fields.1.unwrap(),
            expires_at: self._fields.2,
            fingerprint: self._fields.3,
            key_type: self._fields.4.unwrap(),
            label: self._fields.5,
            public_key_armored: self._fields.6.unwrap(),
            retracted_at: self._fields.7,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(
        self,
        extra_data: BTreeMap<SmolStr, Data<S>>,
    ) -> UserPublicKey<S> {
        UserPublicKey {
            comment: self._fields.0,
            created_at: self._fields.1.unwrap(),
            expires_at: self._fields.2,
            fingerprint: self._fields.3,
            key_type: self._fields.4.unwrap(),
            label: self._fields.5,
            public_key_armored: self._fields.6.unwrap(),
            retracted_at: self._fields.7,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_dev_keytrace_userPublicKey() -> 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("dev.keytrace.userPublicKey"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static("A user-published public key."),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("keyType"),
                                SmolStr::new_static("publicKeyArmored"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("comment"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Optional comment or description."),
                                    ),
                                    max_graphemes: Some(512usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Datetime when this key was created (ISO 8601).",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("expiresAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Datetime when this key expires (ISO 8601).",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("fingerprint"),
                                LexObjectProperty::String(LexString {
                                    description: Some(CowStr::new_static("Key fingerprint.")),
                                    max_graphemes: Some(256usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("keyType"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Format of the public key."),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("label"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Human-readable label for this key (e.g., 'work laptop', 'signing key').",
                                        ),
                                    ),
                                    max_graphemes: Some(128usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("publicKeyArmored"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Full public key in standard text armored format.",
                                        ),
                                    ),
                                    max_length: Some(16384usize),
                                    max_graphemes: Some(16384usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("retractedAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Datetime when this key was retracted. Present only if the key has been retracted (ISO 8601).",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}