// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: zone.stratos.actor.enrollment
//
// 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};
use jacquard_common::deps::bytes::Bytes;

#[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, UriValue};
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};
use crate::zone_stratos::boundary::Domain;
use crate::zone_stratos::actor::enrollment;
/// A record indicating the user is enrolled in a Stratos service. Published to the user's PDS during OAuth enrollment for endpoint discovery by AppViews. Multiple enrollment records are supported — one per Stratos service.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "zone.stratos.actor.enrollment",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Enrollment<S: BosStr = DefaultStr> {
    ///Service attestation vouching for the user's enrollment, boundaries, and signing key.
    pub attestation: enrollment::ServiceAttestation<S>,
    ///List of boundaries the user has access to on this Stratos service.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub boundaries: Option<Vec<Domain<S>>>,
    ///Timestamp when the enrollment was created.
    pub created_at: Datetime,
    ///The Stratos service endpoint URL where this user's private data is stored.
    pub service: UriValue<S>,
    ///The user's P-256 public key as a did:key string, generated by the Stratos service for user-level record signing.
    pub signing_key: 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 EnrollmentGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Enrollment<S>,
}

/// An attestation signed by the Stratos service key. The signed payload is DAG-CBOR encoded {boundaries, did, signingKey} with sorted keys.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct ServiceAttestation<S: BosStr = DefaultStr> {
    ///Raw signature bytes of the DAG-CBOR encoded attestation payload, signed by the service key.
    #[serde(with = "jacquard_common::serde_bytes_helper")]
    pub sig: Bytes,
    ///The Stratos service's public key as a did:key string, used to verify the attestation signature.
    pub signing_key: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct EnrollmentRecord;
impl XrpcResp for EnrollmentRecord {
    const NSID: &'static str = "zone.stratos.actor.enrollment";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = EnrollmentGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Enrollment<S> {
    const NSID: &'static str = "zone.stratos.actor.enrollment";
    type Record = EnrollmentRecord;
}

impl Collection for EnrollmentRecord {
    const NSID: &'static str = "zone.stratos.actor.enrollment";
    type Record = EnrollmentRecord;
}

impl<S: BosStr> LexiconSchema for Enrollment<S> {
    fn nsid() -> &'static str {
        "zone.stratos.actor.enrollment"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_zone_stratos_actor_enrollment()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.boundaries {
            #[allow(unused_comparisons)]
            if value.len() > 50usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("boundaries"),
                    max: 50usize,
                    actual: value.len(),
                });
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for ServiceAttestation<S> {
    fn nsid() -> &'static str {
        "zone.stratos.actor.enrollment"
    }
    fn def_name() -> &'static str {
        "serviceAttestation"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_zone_stratos_actor_enrollment()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

pub mod enrollment_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 CreatedAt;
        type Service;
        type SigningKey;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Attestation = Unset;
        type CreatedAt = Unset;
        type Service = Unset;
        type SigningKey = 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 CreatedAt = St::CreatedAt;
        type Service = St::Service;
        type SigningKey = St::SigningKey;
    }
    ///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 Attestation = St::Attestation;
        type CreatedAt = Set<members::created_at>;
        type Service = St::Service;
        type SigningKey = St::SigningKey;
    }
    ///State transition - sets the `service` field to Set
    pub struct SetService<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetService<St> {}
    impl<St: State> State for SetService<St> {
        type Attestation = St::Attestation;
        type CreatedAt = St::CreatedAt;
        type Service = Set<members::service>;
        type SigningKey = St::SigningKey;
    }
    ///State transition - sets the `signing_key` field to Set
    pub struct SetSigningKey<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetSigningKey<St> {}
    impl<St: State> State for SetSigningKey<St> {
        type Attestation = St::Attestation;
        type CreatedAt = St::CreatedAt;
        type Service = St::Service;
        type SigningKey = Set<members::signing_key>;
    }
    /// 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 `created_at` field
        pub struct created_at(());
        ///Marker type for the `service` field
        pub struct service(());
        ///Marker type for the `signing_key` field
        pub struct signing_key(());
    }
}

/// Builder for constructing an instance of this type.
pub struct EnrollmentBuilder<St: enrollment_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<enrollment::ServiceAttestation<S>>,
        Option<Vec<Domain<S>>>,
        Option<Datetime>,
        Option<UriValue<S>>,
        Option<S>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> Enrollment<S> {
    /// Create a new builder for this type
    pub fn builder() -> EnrollmentBuilder<enrollment_state::Empty, S> {
        EnrollmentBuilder::builder()
    }
}

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

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

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

impl<St: enrollment_state::State, S: BosStr> EnrollmentBuilder<St, S> {
    /// Set the `boundaries` field (optional)
    pub fn boundaries(mut self, value: impl Into<Option<Vec<Domain<S>>>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `boundaries` field to an Option value (optional)
    pub fn maybe_boundaries(mut self, value: Option<Vec<Domain<S>>>) -> Self {
        self._fields.1 = value;
        self
    }
}

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

impl<St, S: BosStr> EnrollmentBuilder<St, S>
where
    St: enrollment_state::State,
    St::Service: enrollment_state::IsUnset,
{
    /// Set the `service` field (required)
    pub fn service(
        mut self,
        value: impl Into<UriValue<S>>,
    ) -> EnrollmentBuilder<enrollment_state::SetService<St>, S> {
        self._fields.3 = Option::Some(value.into());
        EnrollmentBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> EnrollmentBuilder<St, S>
where
    St: enrollment_state::State,
    St::SigningKey: enrollment_state::IsUnset,
{
    /// Set the `signingKey` field (required)
    pub fn signing_key(
        mut self,
        value: impl Into<S>,
    ) -> EnrollmentBuilder<enrollment_state::SetSigningKey<St>, S> {
        self._fields.4 = Option::Some(value.into());
        EnrollmentBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> EnrollmentBuilder<St, S>
where
    St: enrollment_state::State,
    St::Attestation: enrollment_state::IsSet,
    St::CreatedAt: enrollment_state::IsSet,
    St::Service: enrollment_state::IsSet,
    St::SigningKey: enrollment_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Enrollment<S> {
        Enrollment {
            attestation: self._fields.0.unwrap(),
            boundaries: self._fields.1,
            created_at: self._fields.2.unwrap(),
            service: self._fields.3.unwrap(),
            signing_key: self._fields.4.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>>,
    ) -> Enrollment<S> {
        Enrollment {
            attestation: self._fields.0.unwrap(),
            boundaries: self._fields.1,
            created_at: self._fields.2.unwrap(),
            service: self._fields.3.unwrap(),
            signing_key: self._fields.4.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_zone_stratos_actor_enrollment() -> 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("zone.stratos.actor.enrollment"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A record indicating the user is enrolled in a Stratos service. Published to the user's PDS during OAuth enrollment for endpoint discovery by AppViews. Multiple enrollment records are supported — one per Stratos service.",
                        ),
                    ),
                    key: Some(CowStr::new_static("any")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("service"),
                                SmolStr::new_static("signingKey"),
                                SmolStr::new_static("attestation"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("attestation"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("#serviceAttestation"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("boundaries"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "List of boundaries the user has access to on this Stratos service.",
                                        ),
                                    ),
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static(
                                            "zone.stratos.boundary.defs#Domain",
                                        ),
                                        ..Default::default()
                                    }),
                                    max_length: Some(50usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Timestamp when the enrollment was created.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("service"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The Stratos service endpoint URL where this user's private data is stored.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Uri),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("signingKey"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The user's P-256 public key as a did:key string, generated by the Stratos service for user-level record signing.",
                                        ),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("serviceAttestation"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "An attestation signed by the Stratos service key. The signed payload is DAG-CBOR encoded {boundaries, did, signingKey} with sorted keys.",
                        ),
                    ),
                    required: Some(
                        vec![
                            SmolStr::new_static("sig"), SmolStr::new_static("signingKey")
                        ],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("sig"),
                            LexObjectProperty::Bytes(LexBytes { ..Default::default() }),
                        );
                        map.insert(
                            SmolStr::new_static("signingKey"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "The Stratos service's public key as a did:key string, used to verify the attestation signature.",
                                    ),
                                ),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod service_attestation_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 Sig;
        type SigningKey;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Sig = Unset;
        type SigningKey = Unset;
    }
    ///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 Sig = Set<members::sig>;
        type SigningKey = St::SigningKey;
    }
    ///State transition - sets the `signing_key` field to Set
    pub struct SetSigningKey<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetSigningKey<St> {}
    impl<St: State> State for SetSigningKey<St> {
        type Sig = St::Sig;
        type SigningKey = Set<members::signing_key>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `sig` field
        pub struct sig(());
        ///Marker type for the `signing_key` field
        pub struct signing_key(());
    }
}

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

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

impl<S: BosStr> ServiceAttestation<S> {
    /// Create a new builder for this type
    pub fn builder() -> ServiceAttestationBuilder<service_attestation_state::Empty, S> {
        ServiceAttestationBuilder::builder()
    }
}

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

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

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

impl<St, S: BosStr> ServiceAttestationBuilder<St, S>
where
    St: service_attestation_state::State,
    St::SigningKey: service_attestation_state::IsUnset,
{
    /// Set the `signingKey` field (required)
    pub fn signing_key(
        mut self,
        value: impl Into<S>,
    ) -> ServiceAttestationBuilder<service_attestation_state::SetSigningKey<St>, S> {
        self._fields.1 = Option::Some(value.into());
        ServiceAttestationBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ServiceAttestationBuilder<St, S>
where
    St: service_attestation_state::State,
    St::Sig: service_attestation_state::IsSet,
    St::SigningKey: service_attestation_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> ServiceAttestation<S> {
        ServiceAttestation {
            sig: self._fields.0.unwrap(),
            signing_key: self._fields.1.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>>,
    ) -> ServiceAttestation<S> {
        ServiceAttestation {
            sig: self._fields.0.unwrap(),
            signing_key: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}