// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: dev.keytrace.serverPublicKey
//
// 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 signing key for claim attestations. It effectively hosts a JWK on a user's ATProto repo.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "dev.keytrace.serverPublicKey",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct ServerPublicKey<S: BosStr = DefaultStr> {
    ///Optional comment or description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub comment: Option<S>,
    ///JWK public key as a JSON string (RFC 7517 format)
    pub public_jwk: S,
    ///Datetime from which this key is valid (ISO 8601).
    pub valid_from: Datetime,
    ///Datetime until which this key is valid (ISO 8601).
    pub valid_until: Datetime,
    #[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 ServerPublicKeyGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: ServerPublicKey<S>,
}

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

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

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

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

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

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

impl<S: BosStr> LexiconSchema for ServerPublicKey<S> {
    fn nsid() -> &'static str {
        "dev.keytrace.serverPublicKey"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_dev_keytrace_serverPublicKey()
    }
    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,
                    });
                }
            }
        }
        {
            let value = &self.public_jwk;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 512usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("public_jwk"),
                    max: 512usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod server_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 PublicJwk;
        type ValidFrom;
        type ValidUntil;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type PublicJwk = Unset;
        type ValidFrom = Unset;
        type ValidUntil = Unset;
    }
    ///State transition - sets the `public_jwk` field to Set
    pub struct SetPublicJwk<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetPublicJwk<St> {}
    impl<St: State> State for SetPublicJwk<St> {
        type PublicJwk = Set<members::public_jwk>;
        type ValidFrom = St::ValidFrom;
        type ValidUntil = St::ValidUntil;
    }
    ///State transition - sets the `valid_from` field to Set
    pub struct SetValidFrom<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetValidFrom<St> {}
    impl<St: State> State for SetValidFrom<St> {
        type PublicJwk = St::PublicJwk;
        type ValidFrom = Set<members::valid_from>;
        type ValidUntil = St::ValidUntil;
    }
    ///State transition - sets the `valid_until` field to Set
    pub struct SetValidUntil<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetValidUntil<St> {}
    impl<St: State> State for SetValidUntil<St> {
        type PublicJwk = St::PublicJwk;
        type ValidFrom = St::ValidFrom;
        type ValidUntil = Set<members::valid_until>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `public_jwk` field
        pub struct public_jwk(());
        ///Marker type for the `valid_from` field
        pub struct valid_from(());
        ///Marker type for the `valid_until` field
        pub struct valid_until(());
    }
}

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

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

impl<S: BosStr> ServerPublicKey<S> {
    /// Create a new builder for this type
    pub fn builder() -> ServerPublicKeyBuilder<server_public_key_state::Empty, S> {
        ServerPublicKeyBuilder::builder()
    }
}

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

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

impl<St: server_public_key_state::State, S: BosStr> ServerPublicKeyBuilder<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> ServerPublicKeyBuilder<St, S>
where
    St: server_public_key_state::State,
    St::PublicJwk: server_public_key_state::IsUnset,
{
    /// Set the `publicJwk` field (required)
    pub fn public_jwk(
        mut self,
        value: impl Into<S>,
    ) -> ServerPublicKeyBuilder<server_public_key_state::SetPublicJwk<St>, S> {
        self._fields.1 = Option::Some(value.into());
        ServerPublicKeyBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ServerPublicKeyBuilder<St, S>
where
    St: server_public_key_state::State,
    St::ValidFrom: server_public_key_state::IsUnset,
{
    /// Set the `validFrom` field (required)
    pub fn valid_from(
        mut self,
        value: impl Into<Datetime>,
    ) -> ServerPublicKeyBuilder<server_public_key_state::SetValidFrom<St>, S> {
        self._fields.2 = Option::Some(value.into());
        ServerPublicKeyBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ServerPublicKeyBuilder<St, S>
where
    St: server_public_key_state::State,
    St::ValidUntil: server_public_key_state::IsUnset,
{
    /// Set the `validUntil` field (required)
    pub fn valid_until(
        mut self,
        value: impl Into<Datetime>,
    ) -> ServerPublicKeyBuilder<server_public_key_state::SetValidUntil<St>, S> {
        self._fields.3 = Option::Some(value.into());
        ServerPublicKeyBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ServerPublicKeyBuilder<St, S>
where
    St: server_public_key_state::State,
    St::PublicJwk: server_public_key_state::IsSet,
    St::ValidFrom: server_public_key_state::IsSet,
    St::ValidUntil: server_public_key_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> ServerPublicKey<S> {
        ServerPublicKey {
            comment: self._fields.0,
            public_jwk: self._fields.1.unwrap(),
            valid_from: self._fields.2.unwrap(),
            valid_until: self._fields.3.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>>,
    ) -> ServerPublicKey<S> {
        ServerPublicKey {
            comment: self._fields.0,
            public_jwk: self._fields.1.unwrap(),
            valid_from: self._fields.2.unwrap(),
            valid_until: self._fields.3.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_dev_keytrace_serverPublicKey() -> 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.serverPublicKey"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A signing key for claim attestations. It effectively hosts a JWK on a user's ATProto repo.",
                        ),
                    ),
                    key: Some(CowStr::new_static("any")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("publicJwk"),
                                SmolStr::new_static("validFrom"),
                                SmolStr::new_static("validUntil")
                            ],
                        ),
                        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("publicJwk"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "JWK public key as a JSON string (RFC 7517 format)",
                                        ),
                                    ),
                                    max_length: Some(512usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("validFrom"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Datetime from which this key is valid (ISO 8601).",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("validUntil"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Datetime until which this key is valid (ISO 8601).",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}