// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: dev.keytrace.statement
//
// 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 public statement signed by one of the user's own published public keys (dev.keytrace.userPublicKey).

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "dev.keytrace.statement",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Statement<S: BosStr = DefaultStr> {
    ///The statement text that was signed.
    pub content: S,
    ///Datetime when this statement was created (ISO 8601).
    pub created_at: Datetime,
    ///AT URI of the dev.keytrace.userPublicKey record whose private key produced this signature (e.g., at://did:plc:xxx/dev.keytrace.userPublicKey/3k4...)
    pub key_ref: AtUri<S>,
    ///Datetime when this statement was retracted. Present only if the statement has been retracted (ISO 8601).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retracted_at: Option<Datetime>,
    ///Cryptographic signature of the content field, produced by the key referenced in keyRef (PGP cleartext or detached, base64-encoded binary signature).
    pub sig: S,
    ///Optional short subject or title for the statement.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subject: Option<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 StatementGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Statement<S>,
}

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

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

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

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

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

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

impl<S: BosStr> LexiconSchema for Statement<S> {
    fn nsid() -> &'static str {
        "dev.keytrace.statement"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_dev_keytrace_statement()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.content;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 10000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("content"),
                    max: 10000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.content;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 10000usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("content"),
                        max: 10000usize,
                        actual: count,
                    });
                }
            }
        }
        if let Some(ref value) = self.subject {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 256usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("subject"),
                        max: 256usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

pub mod statement_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 Content;
        type CreatedAt;
        type KeyRef;
        type Sig;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Content = Unset;
        type CreatedAt = Unset;
        type KeyRef = Unset;
        type Sig = Unset;
    }
    ///State transition - sets the `content` field to Set
    pub struct SetContent<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetContent<St> {}
    impl<St: State> State for SetContent<St> {
        type Content = Set<members::content>;
        type CreatedAt = St::CreatedAt;
        type KeyRef = St::KeyRef;
        type Sig = St::Sig;
    }
    ///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 Content = St::Content;
        type CreatedAt = Set<members::created_at>;
        type KeyRef = St::KeyRef;
        type Sig = St::Sig;
    }
    ///State transition - sets the `key_ref` field to Set
    pub struct SetKeyRef<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetKeyRef<St> {}
    impl<St: State> State for SetKeyRef<St> {
        type Content = St::Content;
        type CreatedAt = St::CreatedAt;
        type KeyRef = Set<members::key_ref>;
        type Sig = St::Sig;
    }
    ///State transition - sets the `sig` field to Set
    pub struct SetSig<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetSig<St> {}
    impl<St: State> State for SetSig<St> {
        type Content = St::Content;
        type CreatedAt = St::CreatedAt;
        type KeyRef = St::KeyRef;
        type Sig = Set<members::sig>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `content` field
        pub struct content(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `key_ref` field
        pub struct key_ref(());
        ///Marker type for the `sig` field
        pub struct sig(());
    }
}

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

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

impl<S: BosStr> Statement<S> {
    /// Create a new builder for this type
    pub fn builder() -> StatementBuilder<statement_state::Empty, S> {
        StatementBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> StatementBuilder<St, S>
where
    St: statement_state::State,
    St::Content: statement_state::IsUnset,
{
    /// Set the `content` field (required)
    pub fn content(
        mut self,
        value: impl Into<S>,
    ) -> StatementBuilder<statement_state::SetContent<St>, S> {
        self._fields.0 = Option::Some(value.into());
        StatementBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

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

impl<St, S: BosStr> StatementBuilder<St, S>
where
    St: statement_state::State,
    St::KeyRef: statement_state::IsUnset,
{
    /// Set the `keyRef` field (required)
    pub fn key_ref(
        mut self,
        value: impl Into<AtUri<S>>,
    ) -> StatementBuilder<statement_state::SetKeyRef<St>, S> {
        self._fields.2 = Option::Some(value.into());
        StatementBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: statement_state::State, S: BosStr> StatementBuilder<St, S> {
    /// Set the `retractedAt` field (optional)
    pub fn retracted_at(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.3 = 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.3 = value;
        self
    }
}

impl<St, S: BosStr> StatementBuilder<St, S>
where
    St: statement_state::State,
    St::Sig: statement_state::IsUnset,
{
    /// Set the `sig` field (required)
    pub fn sig(
        mut self,
        value: impl Into<S>,
    ) -> StatementBuilder<statement_state::SetSig<St>, S> {
        self._fields.4 = Option::Some(value.into());
        StatementBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

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

impl<St, S: BosStr> StatementBuilder<St, S>
where
    St: statement_state::State,
    St::Content: statement_state::IsSet,
    St::CreatedAt: statement_state::IsSet,
    St::KeyRef: statement_state::IsSet,
    St::Sig: statement_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Statement<S> {
        Statement {
            content: self._fields.0.unwrap(),
            created_at: self._fields.1.unwrap(),
            key_ref: self._fields.2.unwrap(),
            retracted_at: self._fields.3,
            sig: self._fields.4.unwrap(),
            subject: self._fields.5,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(
        self,
        extra_data: BTreeMap<SmolStr, Data<S>>,
    ) -> Statement<S> {
        Statement {
            content: self._fields.0.unwrap(),
            created_at: self._fields.1.unwrap(),
            key_ref: self._fields.2.unwrap(),
            retracted_at: self._fields.3,
            sig: self._fields.4.unwrap(),
            subject: self._fields.5,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_dev_keytrace_statement() -> 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.statement"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A public statement signed by one of the user's own published public keys (dev.keytrace.userPublicKey).",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("content"),
                                SmolStr::new_static("keyRef"), SmolStr::new_static("sig"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("content"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("The statement text that was signed."),
                                    ),
                                    max_length: Some(10000usize),
                                    max_graphemes: Some(10000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Datetime when this statement was created (ISO 8601).",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("keyRef"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "AT URI of the dev.keytrace.userPublicKey record whose private key produced this signature (e.g., at://did:plc:xxx/dev.keytrace.userPublicKey/3k4...)",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::AtUri),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("retractedAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Datetime when this statement was retracted. Present only if the statement has been retracted (ISO 8601).",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("sig"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Cryptographic signature of the content field, produced by the key referenced in keyRef (PGP cleartext or detached, base64-encoded binary signature).",
                                        ),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("subject"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Optional short subject or title for the statement.",
                                        ),
                                    ),
                                    max_graphemes: Some(256usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}