// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: sh.tangled.knot.listKeys
//
// 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::string::{Did, Datetime};
use jacquard_derive::{IntoStatic, lexicon, open_union};
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::sh_tangled::knot::list_keys;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct ListKeys<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub cursor: Option<CowStr<'a>>,
    ///Defaults to `100`. Min: 1. Max: 1000.
    #[serde(default = "_default_limit")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<i64>,
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct ListKeysOutput<'a> {
    ///Pagination cursor for next page
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub cursor: Option<CowStr<'a>>,
    #[serde(borrow)]
    pub keys: Vec<list_keys::PublicKey<'a>>,
}


#[open_union]
#[derive(
    Serialize,
    Deserialize,
    Debug,
    Clone,
    PartialEq,
    Eq,
    thiserror::Error,
    miette::Diagnostic,
    IntoStatic
)]

#[serde(tag = "error", content = "message")]
#[serde(bound(deserialize = "'de: 'a"))]
pub enum ListKeysError<'a> {
    /// Failed to retrieve public keys
    #[serde(rename = "InternalServerError")]
    InternalServerError(Option<CowStr<'a>>),
}

impl core::fmt::Display for ListKeysError<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::InternalServerError(msg) => {
                write!(f, "InternalServerError")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::Unknown(err) => write!(f, "Unknown error: {:?}", err),
        }
    }
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct PublicKey<'a> {
    ///Key upload timestamp
    pub created_at: Datetime,
    ///DID associated with the public key
    #[serde(borrow)]
    pub did: Did<'a>,
    ///Public key contents
    #[serde(borrow)]
    pub key: CowStr<'a>,
}

/// Response type for sh.tangled.knot.listKeys
pub struct ListKeysResponse;
impl jacquard_common::xrpc::XrpcResp for ListKeysResponse {
    const NSID: &'static str = "sh.tangled.knot.listKeys";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = ListKeysOutput<'de>;
    type Err<'de> = ListKeysError<'de>;
}

impl<'a> jacquard_common::xrpc::XrpcRequest for ListKeys<'a> {
    const NSID: &'static str = "sh.tangled.knot.listKeys";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Query;
    type Response = ListKeysResponse;
}

/// Endpoint type for sh.tangled.knot.listKeys
pub struct ListKeysRequest;
impl jacquard_common::xrpc::XrpcEndpoint for ListKeysRequest {
    const PATH: &'static str = "/xrpc/sh.tangled.knot.listKeys";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Query;
    type Request<'de> = ListKeys<'de>;
    type Response = ListKeysResponse;
}

impl<'a> LexiconSchema for PublicKey<'a> {
    fn nsid() -> &'static str {
        "sh.tangled.knot.listKeys"
    }
    fn def_name() -> &'static str {
        "publicKey"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_sh_tangled_knot_listKeys()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.key;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 4096usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("key"),
                    max: 4096usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

fn _default_limit() -> Option<i64> {
    Some(100i64)
}

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

/// Builder for constructing an instance of this type
pub struct ListKeysBuilder<'a, S: list_keys_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (Option<CowStr<'a>>, Option<i64>),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> ListKeys<'a> {
    /// Create a new builder for this type
    pub fn new() -> ListKeysBuilder<'a, list_keys_state::Empty> {
        ListKeysBuilder::new()
    }
}

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

impl<'a, S: list_keys_state::State> ListKeysBuilder<'a, S> {
    /// Set the `cursor` field (optional)
    pub fn cursor(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `cursor` field to an Option value (optional)
    pub fn maybe_cursor(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<'a, S: list_keys_state::State> ListKeysBuilder<'a, S> {
    /// Set the `limit` field (optional)
    pub fn limit(mut self, value: impl Into<Option<i64>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `limit` field to an Option value (optional)
    pub fn maybe_limit(mut self, value: Option<i64>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<'a, S> ListKeysBuilder<'a, S>
where
    S: list_keys_state::State,
{
    /// Build the final struct
    pub fn build(self) -> ListKeys<'a> {
        ListKeys {
            cursor: self._fields.0,
            limit: self._fields.1,
        }
    }
}

pub mod 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 Did;
        type Key;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedAt = Unset;
        type Did = Unset;
        type Key = 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>;
        type Did = S::Did;
        type Key = S::Key;
    }
    ///State transition - sets the `did` field to Set
    pub struct SetDid<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetDid<S> {}
    impl<S: State> State for SetDid<S> {
        type CreatedAt = S::CreatedAt;
        type Did = Set<members::did>;
        type Key = S::Key;
    }
    ///State transition - sets the `key` field to Set
    pub struct SetKey<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetKey<S> {}
    impl<S: State> State for SetKey<S> {
        type CreatedAt = S::CreatedAt;
        type Did = S::Did;
        type Key = Set<members::key>;
    }
    /// 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 `did` field
        pub struct did(());
        ///Marker type for the `key` field
        pub struct key(());
    }
}

/// Builder for constructing an instance of this type
pub struct PublicKeyBuilder<'a, S: public_key_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (Option<Datetime>, Option<Did<'a>>, Option<CowStr<'a>>),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> PublicKey<'a> {
    /// Create a new builder for this type
    pub fn new() -> PublicKeyBuilder<'a, public_key_state::Empty> {
        PublicKeyBuilder::new()
    }
}

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

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

impl<'a, S> PublicKeyBuilder<'a, S>
where
    S: public_key_state::State,
    S::Did: public_key_state::IsUnset,
{
    /// Set the `did` field (required)
    pub fn did(
        mut self,
        value: impl Into<Did<'a>>,
    ) -> PublicKeyBuilder<'a, public_key_state::SetDid<S>> {
        self._fields.1 = Option::Some(value.into());
        PublicKeyBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> PublicKeyBuilder<'a, S>
where
    S: public_key_state::State,
    S::Key: public_key_state::IsUnset,
{
    /// Set the `key` field (required)
    pub fn key(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> PublicKeyBuilder<'a, public_key_state::SetKey<S>> {
        self._fields.2 = Option::Some(value.into());
        PublicKeyBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> PublicKeyBuilder<'a, S>
where
    S: public_key_state::State,
    S::CreatedAt: public_key_state::IsSet,
    S::Did: public_key_state::IsSet,
    S::Key: public_key_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> PublicKey<'a> {
        PublicKey {
            created_at: self._fields.0.unwrap(),
            did: self._fields.1.unwrap(),
            key: self._fields.2.unwrap(),
            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>,
        >,
    ) -> PublicKey<'a> {
        PublicKey {
            created_at: self._fields.0.unwrap(),
            did: self._fields.1.unwrap(),
            key: self._fields.2.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_sh_tangled_knot_listKeys() -> 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("sh.tangled.knot.listKeys"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::XrpcQuery(LexXrpcQuery {
                    parameters: Some(
                        LexXrpcQueryParameter::Params(LexXrpcParameters {
                            properties: {
                                #[allow(unused_mut)]
                                let mut map = BTreeMap::new();
                                map.insert(
                                    SmolStr::new_static("cursor"),
                                    LexXrpcParametersProperty::String(LexString {
                                        description: Some(CowStr::new_static("Pagination cursor")),
                                        ..Default::default()
                                    }),
                                );
                                map.insert(
                                    SmolStr::new_static("limit"),
                                    LexXrpcParametersProperty::Integer(LexInteger {
                                        ..Default::default()
                                    }),
                                );
                                map
                            },
                            ..Default::default()
                        }),
                    ),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("publicKey"),
                LexUserType::Object(LexObject {
                    required: Some(
                        vec![
                            SmolStr::new_static("did"), SmolStr::new_static("key"),
                            SmolStr::new_static("createdAt")
                        ],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("createdAt"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Key upload timestamp"),
                                ),
                                format: Some(LexStringFormat::Datetime),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("did"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("DID associated with the public key"),
                                ),
                                format: Some(LexStringFormat::Did),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("key"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Public key contents"),
                                ),
                                max_length: Some(4096usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}