// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: dev.keytrace.signature
//
// 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::string::{AtUri, Datetime};
use jacquard_common::types::value::Data;
use jacquard_derive::IntoStatic;
use jacquard_lexicon::lexicon::LexiconDoc;
use jacquard_lexicon::schema::LexiconSchema;

#[allow(unused_imports)]
use jacquard_lexicon::validation::{ConstraintError, ValidationPath};
use serde::{Serialize, Deserialize};
/// A cryptographic signature attesting to a claim

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Signature<S: BosStr = DefaultStr> {
    ///The cryptographic signature (base64-encoded).
    pub attestation: S,
    ///Optional comment or description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub comment: Option<S>,
    ///Key identifier (e.g., date in YYYY-MM-DD format).
    pub kid: S,
    ///Datetime when this signature was retracted. Present only if the signature has been retracted (ISO 8601).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retracted_at: Option<Datetime>,
    ///Datetime when the signature was created (ISO 8601).
    pub signed_at: Datetime,
    ///Ordered list of field names included in the signed payload (e.g., ['did', 'subject', 'type', 'verifiedAt'])
    pub signed_fields: Vec<S>,
    ///AT URI reference to the signing key record published by the verification service (e.g., at://did:plc:serviceaccount/dev.keytrace.serverPublicKey/2024-01-15).
    pub src: AtUri<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

impl<S: BosStr> LexiconSchema for Signature<S> {
    fn nsid() -> &'static str {
        "dev.keytrace.signature"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_dev_keytrace_signature()
    }
    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,
                    });
                }
            }
        }
        Ok(())
    }
}

pub mod signature_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 Attestation;
        type Kid;
        type SignedAt;
        type SignedFields;
        type Src;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Attestation = Unset;
        type Kid = Unset;
        type SignedAt = Unset;
        type SignedFields = Unset;
        type Src = Unset;
    }
    ///State transition - sets the `attestation` field to Set
    pub struct SetAttestation<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetAttestation<St> {}
    impl<St: State> State for SetAttestation<St> {
        type Attestation = Set<members::attestation>;
        type Kid = St::Kid;
        type SignedAt = St::SignedAt;
        type SignedFields = St::SignedFields;
        type Src = St::Src;
    }
    ///State transition - sets the `kid` field to Set
    pub struct SetKid<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetKid<St> {}
    impl<St: State> State for SetKid<St> {
        type Attestation = St::Attestation;
        type Kid = Set<members::kid>;
        type SignedAt = St::SignedAt;
        type SignedFields = St::SignedFields;
        type Src = St::Src;
    }
    ///State transition - sets the `signed_at` field to Set
    pub struct SetSignedAt<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetSignedAt<St> {}
    impl<St: State> State for SetSignedAt<St> {
        type Attestation = St::Attestation;
        type Kid = St::Kid;
        type SignedAt = Set<members::signed_at>;
        type SignedFields = St::SignedFields;
        type Src = St::Src;
    }
    ///State transition - sets the `signed_fields` field to Set
    pub struct SetSignedFields<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetSignedFields<St> {}
    impl<St: State> State for SetSignedFields<St> {
        type Attestation = St::Attestation;
        type Kid = St::Kid;
        type SignedAt = St::SignedAt;
        type SignedFields = Set<members::signed_fields>;
        type Src = St::Src;
    }
    ///State transition - sets the `src` field to Set
    pub struct SetSrc<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetSrc<St> {}
    impl<St: State> State for SetSrc<St> {
        type Attestation = St::Attestation;
        type Kid = St::Kid;
        type SignedAt = St::SignedAt;
        type SignedFields = St::SignedFields;
        type Src = Set<members::src>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `attestation` field
        pub struct attestation(());
        ///Marker type for the `kid` field
        pub struct kid(());
        ///Marker type for the `signed_at` field
        pub struct signed_at(());
        ///Marker type for the `signed_fields` field
        pub struct signed_fields(());
        ///Marker type for the `src` field
        pub struct src(());
    }
}

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

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

impl<S: BosStr> Signature<S> {
    /// Create a new builder for this type
    pub fn builder() -> SignatureBuilder<signature_state::Empty, S> {
        SignatureBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> SignatureBuilder<St, S>
where
    St: signature_state::State,
    St::Attestation: signature_state::IsUnset,
{
    /// Set the `attestation` field (required)
    pub fn attestation(
        mut self,
        value: impl Into<S>,
    ) -> SignatureBuilder<signature_state::SetAttestation<St>, S> {
        self._fields.0 = Option::Some(value.into());
        SignatureBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

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

impl<St, S: BosStr> SignatureBuilder<St, S>
where
    St: signature_state::State,
    St::Kid: signature_state::IsUnset,
{
    /// Set the `kid` field (required)
    pub fn kid(
        mut self,
        value: impl Into<S>,
    ) -> SignatureBuilder<signature_state::SetKid<St>, S> {
        self._fields.2 = Option::Some(value.into());
        SignatureBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: signature_state::State, S: BosStr> SignatureBuilder<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> SignatureBuilder<St, S>
where
    St: signature_state::State,
    St::SignedAt: signature_state::IsUnset,
{
    /// Set the `signedAt` field (required)
    pub fn signed_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> SignatureBuilder<signature_state::SetSignedAt<St>, S> {
        self._fields.4 = Option::Some(value.into());
        SignatureBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> SignatureBuilder<St, S>
where
    St: signature_state::State,
    St::SignedFields: signature_state::IsUnset,
{
    /// Set the `signedFields` field (required)
    pub fn signed_fields(
        mut self,
        value: impl Into<Vec<S>>,
    ) -> SignatureBuilder<signature_state::SetSignedFields<St>, S> {
        self._fields.5 = Option::Some(value.into());
        SignatureBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> SignatureBuilder<St, S>
where
    St: signature_state::State,
    St::Src: signature_state::IsUnset,
{
    /// Set the `src` field (required)
    pub fn src(
        mut self,
        value: impl Into<AtUri<S>>,
    ) -> SignatureBuilder<signature_state::SetSrc<St>, S> {
        self._fields.6 = Option::Some(value.into());
        SignatureBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> SignatureBuilder<St, S>
where
    St: signature_state::State,
    St::Attestation: signature_state::IsSet,
    St::Kid: signature_state::IsSet,
    St::SignedAt: signature_state::IsSet,
    St::SignedFields: signature_state::IsSet,
    St::Src: signature_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Signature<S> {
        Signature {
            attestation: self._fields.0.unwrap(),
            comment: self._fields.1,
            kid: self._fields.2.unwrap(),
            retracted_at: self._fields.3,
            signed_at: self._fields.4.unwrap(),
            signed_fields: self._fields.5.unwrap(),
            src: self._fields.6.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>>,
    ) -> Signature<S> {
        Signature {
            attestation: self._fields.0.unwrap(),
            comment: self._fields.1,
            kid: self._fields.2.unwrap(),
            retracted_at: self._fields.3,
            signed_at: self._fields.4.unwrap(),
            signed_fields: self._fields.5.unwrap(),
            src: self._fields.6.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_dev_keytrace_signature() -> 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.signature"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "A cryptographic signature attesting to a claim",
                        ),
                    ),
                    required: Some(
                        vec![
                            SmolStr::new_static("kid"), SmolStr::new_static("src"),
                            SmolStr::new_static("signedAt"),
                            SmolStr::new_static("attestation"),
                            SmolStr::new_static("signedFields")
                        ],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("attestation"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "The cryptographic signature (base64-encoded).",
                                    ),
                                ),
                                ..Default::default()
                            }),
                        );
                        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("kid"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "Key identifier (e.g., date in YYYY-MM-DD format).",
                                    ),
                                ),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("retractedAt"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "Datetime when this signature was retracted. Present only if the signature has been retracted (ISO 8601).",
                                    ),
                                ),
                                format: Some(LexStringFormat::Datetime),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("signedAt"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "Datetime when the signature was created (ISO 8601).",
                                    ),
                                ),
                                format: Some(LexStringFormat::Datetime),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("signedFields"),
                            LexObjectProperty::Array(LexArray {
                                description: Some(
                                    CowStr::new_static(
                                        "Ordered list of field names included in the signed payload (e.g., ['did', 'subject', 'type', 'verifiedAt'])",
                                    ),
                                ),
                                items: LexArrayItem::String(LexString {
                                    ..Default::default()
                                }),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("src"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "AT URI reference to the signing key record published by the verification service (e.g., at://did:plc:serviceaccount/dev.keytrace.serverPublicKey/2024-01-15).",
                                    ),
                                ),
                                format: Some(LexStringFormat::AtUri),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}