// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: ch.indiemusi.alpha.grant
//
// 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::{Did, 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 cryptographic grant allowing a streaming service to decrypt the artist's music catalog. This record contains the master content key encrypted with the service's public key.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "ch.indiemusi.alpha.grant",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Grant<S: BosStr = DefaultStr> {
    ///When the grant was created
    pub created_at: Datetime,
    ///Optional expiration date. After this, the grant should be considered revoked.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<Datetime>,
    ///The DID of the streaming service being authorized
    pub service_did: Did<S>,
    ///The Master Content Key (32 bytes) encrypted with the service's public key, base64-encoded. Only the service can decrypt this with their private key.
    pub wrapped_master_key: S,
    ///Base64-encoded IV (12 bytes) used to encrypt the master key. Only present for AES-GCM wrapping; empty for RSA-OAEP.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wrapped_master_key_iv: Option<S>,
    ///The algorithm used to wrap the master key. Currently RSA-OAEP (asymmetric, using the service's public key).  Defaults to `"RSA-OAEP"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default = "_default_grant_wrapping_algorithm")]
    pub wrapping_algorithm: 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 GrantGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Grant<S>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct GrantRecord;
impl XrpcResp for GrantRecord {
    const NSID: &'static str = "ch.indiemusi.alpha.grant";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = GrantGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Grant<S> {
    const NSID: &'static str = "ch.indiemusi.alpha.grant";
    type Record = GrantRecord;
}

impl Collection for GrantRecord {
    const NSID: &'static str = "ch.indiemusi.alpha.grant";
    type Record = GrantRecord;
}

impl<S: BosStr> LexiconSchema for Grant<S> {
    fn nsid() -> &'static str {
        "ch.indiemusi.alpha.grant"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_ch_indiemusi_alpha_grant()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.service_did;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 256usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("service_did"),
                    max: 256usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.wrapped_master_key;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 512usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("wrapped_master_key"),
                    max: 512usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.wrapped_master_key_iv {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 32usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("wrapped_master_key_iv"),
                    max: 32usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.wrapping_algorithm {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 50usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("wrapping_algorithm"),
                    max: 50usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

fn _default_grant_wrapping_algorithm<S: FromStaticStr>() -> ::core::option::Option<S> {
    Some(S::from_static("RSA-OAEP"))
}

pub mod grant_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 ServiceDid;
        type WrappedMasterKey;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedAt = Unset;
        type ServiceDid = Unset;
        type WrappedMasterKey = Unset;
    }
    ///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 CreatedAt = Set<members::created_at>;
        type ServiceDid = St::ServiceDid;
        type WrappedMasterKey = St::WrappedMasterKey;
    }
    ///State transition - sets the `service_did` field to Set
    pub struct SetServiceDid<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetServiceDid<St> {}
    impl<St: State> State for SetServiceDid<St> {
        type CreatedAt = St::CreatedAt;
        type ServiceDid = Set<members::service_did>;
        type WrappedMasterKey = St::WrappedMasterKey;
    }
    ///State transition - sets the `wrapped_master_key` field to Set
    pub struct SetWrappedMasterKey<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetWrappedMasterKey<St> {}
    impl<St: State> State for SetWrappedMasterKey<St> {
        type CreatedAt = St::CreatedAt;
        type ServiceDid = St::ServiceDid;
        type WrappedMasterKey = Set<members::wrapped_master_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 `service_did` field
        pub struct service_did(());
        ///Marker type for the `wrapped_master_key` field
        pub struct wrapped_master_key(());
    }
}

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

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

impl<S: BosStr> Grant<S> {
    /// Create a new builder for this type
    pub fn builder() -> GrantBuilder<grant_state::Empty, S> {
        GrantBuilder::builder()
    }
}

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

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

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

impl<St: grant_state::State, S: BosStr> GrantBuilder<St, S> {
    /// Set the `expiresAt` field (optional)
    pub fn expires_at(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `expiresAt` field to an Option value (optional)
    pub fn maybe_expires_at(mut self, value: Option<Datetime>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<St, S: BosStr> GrantBuilder<St, S>
where
    St: grant_state::State,
    St::ServiceDid: grant_state::IsUnset,
{
    /// Set the `serviceDid` field (required)
    pub fn service_did(
        mut self,
        value: impl Into<Did<S>>,
    ) -> GrantBuilder<grant_state::SetServiceDid<St>, S> {
        self._fields.2 = Option::Some(value.into());
        GrantBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> GrantBuilder<St, S>
where
    St: grant_state::State,
    St::WrappedMasterKey: grant_state::IsUnset,
{
    /// Set the `wrappedMasterKey` field (required)
    pub fn wrapped_master_key(
        mut self,
        value: impl Into<S>,
    ) -> GrantBuilder<grant_state::SetWrappedMasterKey<St>, S> {
        self._fields.3 = Option::Some(value.into());
        GrantBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: grant_state::State, S: BosStr> GrantBuilder<St, S> {
    /// Set the `wrappedMasterKeyIv` field (optional)
    pub fn wrapped_master_key_iv(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `wrappedMasterKeyIv` field to an Option value (optional)
    pub fn maybe_wrapped_master_key_iv(mut self, value: Option<S>) -> Self {
        self._fields.4 = value;
        self
    }
}

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

impl<St, S: BosStr> GrantBuilder<St, S>
where
    St: grant_state::State,
    St::CreatedAt: grant_state::IsSet,
    St::ServiceDid: grant_state::IsSet,
    St::WrappedMasterKey: grant_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Grant<S> {
        Grant {
            created_at: self._fields.0.unwrap(),
            expires_at: self._fields.1,
            service_did: self._fields.2.unwrap(),
            wrapped_master_key: self._fields.3.unwrap(),
            wrapped_master_key_iv: self._fields.4,
            wrapping_algorithm: self
                ._fields
                .5
                .or_else(|| Some(S::from_static("RSA-OAEP"))),
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(self, extra_data: BTreeMap<SmolStr, Data<S>>) -> Grant<S> {
        Grant {
            created_at: self._fields.0.unwrap(),
            expires_at: self._fields.1,
            service_did: self._fields.2.unwrap(),
            wrapped_master_key: self._fields.3.unwrap(),
            wrapped_master_key_iv: self._fields.4,
            wrapping_algorithm: self
                ._fields
                .5
                .or_else(|| Some(S::from_static("RSA-OAEP"))),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_ch_indiemusi_alpha_grant() -> 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("ch.indiemusi.alpha.grant"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A cryptographic grant allowing a streaming service to decrypt the artist's music catalog. This record contains the master content key encrypted with the service's public key.",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("serviceDid"),
                                SmolStr::new_static("wrappedMasterKey"),
                                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("When the grant was created"),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("expiresAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Optional expiration date. After this, the grant should be considered revoked.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("serviceDid"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The DID of the streaming service being authorized",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Did),
                                    max_length: Some(256usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("wrappedMasterKey"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The Master Content Key (32 bytes) encrypted with the service's public key, base64-encoded. Only the service can decrypt this with their private key.",
                                        ),
                                    ),
                                    max_length: Some(512usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("wrappedMasterKeyIv"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Base64-encoded IV (12 bytes) used to encrypt the master key. Only present for AES-GCM wrapping; empty for RSA-OAEP.",
                                        ),
                                    ),
                                    max_length: Some(32usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("wrappingAlgorithm"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The algorithm used to wrap the master key. Currently RSA-OAEP (asymmetric, using the service's public key).",
                                        ),
                                    ),
                                    max_length: Some(50usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}