// @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;

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
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::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.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Grant<'a> {
    ///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
    #[serde(borrow)]
    pub service_did: Did<'a>,
    ///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.
    #[serde(borrow)]
    pub wrapped_master_key: CowStr<'a>,
    ///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")]
    #[serde(borrow)]
    pub wrapped_master_key_iv: Option<CowStr<'a>>,
    ///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")]
    #[serde(borrow)]
    pub wrapping_algorithm: Option<CowStr<'a>>,
}

/// 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<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub cid: Option<Cid<'a>>,
    #[serde(borrow)]
    pub uri: AtUri<'a>,
    #[serde(borrow)]
    pub value: Grant<'a>,
}

impl<'a> Grant<'a> {
    pub fn uri(
        uri: impl Into<CowStr<'a>>,
    ) -> Result<RecordUri<'a, GrantRecord>, UriError> {
        RecordUri::try_from_uri(AtUri::new_cow(uri.into())?)
    }
}

/// 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<'de> = GrantGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

impl From<GrantGetRecordOutput<'_>> for Grant<'_> {
    fn from(output: GrantGetRecordOutput<'_>) -> Self {
        use jacquard_common::IntoStatic;
        output.value.into_static()
    }
}

impl Collection for Grant<'_> {
    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<'a> LexiconSchema for Grant<'a> {
    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() -> Option<CowStr<'static>> {
    Some(CowStr::from("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 ServiceDid;
        type CreatedAt;
        type WrappedMasterKey;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type ServiceDid = Unset;
        type CreatedAt = Unset;
        type WrappedMasterKey = Unset;
    }
    ///State transition - sets the `service_did` field to Set
    pub struct SetServiceDid<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetServiceDid<S> {}
    impl<S: State> State for SetServiceDid<S> {
        type ServiceDid = Set<members::service_did>;
        type CreatedAt = S::CreatedAt;
        type WrappedMasterKey = S::WrappedMasterKey;
    }
    ///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 ServiceDid = S::ServiceDid;
        type CreatedAt = Set<members::created_at>;
        type WrappedMasterKey = S::WrappedMasterKey;
    }
    ///State transition - sets the `wrapped_master_key` field to Set
    pub struct SetWrappedMasterKey<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetWrappedMasterKey<S> {}
    impl<S: State> State for SetWrappedMasterKey<S> {
        type ServiceDid = S::ServiceDid;
        type CreatedAt = S::CreatedAt;
        type WrappedMasterKey = Set<members::wrapped_master_key>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `service_did` field
        pub struct service_did(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `wrapped_master_key` field
        pub struct wrapped_master_key(());
    }
}

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

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

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

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

impl<'a, S: grant_state::State> GrantBuilder<'a, 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<'a, S> GrantBuilder<'a, S>
where
    S: grant_state::State,
    S::ServiceDid: grant_state::IsUnset,
{
    /// Set the `serviceDid` field (required)
    pub fn service_did(
        mut self,
        value: impl Into<Did<'a>>,
    ) -> GrantBuilder<'a, grant_state::SetServiceDid<S>> {
        self._fields.2 = Option::Some(value.into());
        GrantBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

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

impl<'a, S: grant_state::State> GrantBuilder<'a, S> {
    /// Set the `wrappedMasterKeyIv` field (optional)
    pub fn wrapped_master_key_iv(
        mut self,
        value: impl Into<Option<CowStr<'a>>>,
    ) -> 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<CowStr<'a>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<'a, S: grant_state::State> GrantBuilder<'a, S> {
    /// Set the `wrappingAlgorithm` field (optional)
    pub fn wrapping_algorithm(mut self, value: impl Into<Option<CowStr<'a>>>) -> 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<CowStr<'a>>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<'a, S> GrantBuilder<'a, S>
where
    S: grant_state::State,
    S::ServiceDid: grant_state::IsSet,
    S::CreatedAt: grant_state::IsSet,
    S::WrappedMasterKey: grant_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Grant<'a> {
        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(CowStr::from("RSA-OAEP"))),
            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>,
        >,
    ) -> Grant<'a> {
        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(CowStr::from("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()
    }
}