// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: ch.indiemusi.alpha.track
//
// 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::blob::BlobRef;
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::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};
/// An encrypted audio track. The audio blob is encrypted with AES-GCM-256, and the decryption key is wrapped and stored in grant records.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Track<'a> {
    ///The encrypted audio file
    #[serde(borrow)]
    pub audio_blob: BlobRef<'a>,
    ///Timestamp when the track was uploaded
    pub created_at: Datetime,
    ///Base64-encoded IV (12 bytes) used to encrypt the audio with the content key
    #[serde(borrow)]
    pub encrypted_content_iv: CowStr<'a>,
    ///The symmetric algorithm used to encrypt the audio blob  Defaults to `"AES-GCM-256"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default = "_default_track_encryption_algorithm")]
    #[serde(borrow)]
    pub encryption_algorithm: Option<CowStr<'a>>,
    ///Track title
    #[serde(borrow)]
    pub title: 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 TrackGetRecordOutput<'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: Track<'a>,
}

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

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

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

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

impl Collection for Track<'_> {
    const NSID: &'static str = "ch.indiemusi.alpha.track";
    type Record = TrackRecord;
}

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

impl<'a> LexiconSchema for Track<'a> {
    fn nsid() -> &'static str {
        "ch.indiemusi.alpha.track"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_ch_indiemusi_alpha_track()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.audio_blob;
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &["audio/wav", "audio/mpeg", "audio/flac"];
                let matched = accepted
                    .iter()
                    .any(|pattern| {
                        if *pattern == "*/*" {
                            true
                        } else if pattern.ends_with("/*") {
                            let prefix = &pattern[..pattern.len() - 2];
                            mime.starts_with(prefix)
                                && mime.as_bytes().get(prefix.len()) == Some(&b'/')
                        } else {
                            mime == *pattern
                        }
                    });
                if !matched {
                    return Err(ConstraintError::BlobMimeTypeNotAccepted {
                        path: ValidationPath::from_field("audio_blob"),
                        accepted: vec![
                            "audio/wav".to_string(), "audio/mpeg".to_string(),
                            "audio/flac".to_string()
                        ],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        {
            let value = &self.encrypted_content_iv;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 32usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("encrypted_content_iv"),
                    max: 32usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.encryption_algorithm {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 50usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("encryption_algorithm"),
                    max: 50usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.title;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 255usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("title"),
                    max: 255usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

fn _default_track_encryption_algorithm() -> Option<CowStr<'static>> {
    Some(CowStr::from("AES-GCM-256"))
}

pub mod track_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 EncryptedContentIv;
        type CreatedAt;
        type Title;
        type AudioBlob;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type EncryptedContentIv = Unset;
        type CreatedAt = Unset;
        type Title = Unset;
        type AudioBlob = Unset;
    }
    ///State transition - sets the `encrypted_content_iv` field to Set
    pub struct SetEncryptedContentIv<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetEncryptedContentIv<S> {}
    impl<S: State> State for SetEncryptedContentIv<S> {
        type EncryptedContentIv = Set<members::encrypted_content_iv>;
        type CreatedAt = S::CreatedAt;
        type Title = S::Title;
        type AudioBlob = S::AudioBlob;
    }
    ///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 EncryptedContentIv = S::EncryptedContentIv;
        type CreatedAt = Set<members::created_at>;
        type Title = S::Title;
        type AudioBlob = S::AudioBlob;
    }
    ///State transition - sets the `title` field to Set
    pub struct SetTitle<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetTitle<S> {}
    impl<S: State> State for SetTitle<S> {
        type EncryptedContentIv = S::EncryptedContentIv;
        type CreatedAt = S::CreatedAt;
        type Title = Set<members::title>;
        type AudioBlob = S::AudioBlob;
    }
    ///State transition - sets the `audio_blob` field to Set
    pub struct SetAudioBlob<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetAudioBlob<S> {}
    impl<S: State> State for SetAudioBlob<S> {
        type EncryptedContentIv = S::EncryptedContentIv;
        type CreatedAt = S::CreatedAt;
        type Title = S::Title;
        type AudioBlob = Set<members::audio_blob>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `encrypted_content_iv` field
        pub struct encrypted_content_iv(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `title` field
        pub struct title(());
        ///Marker type for the `audio_blob` field
        pub struct audio_blob(());
    }
}

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

impl<'a> Track<'a> {
    /// Create a new builder for this type
    pub fn new() -> TrackBuilder<'a, track_state::Empty> {
        TrackBuilder::new()
    }
}

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

impl<'a, S> TrackBuilder<'a, S>
where
    S: track_state::State,
    S::AudioBlob: track_state::IsUnset,
{
    /// Set the `audioBlob` field (required)
    pub fn audio_blob(
        mut self,
        value: impl Into<BlobRef<'a>>,
    ) -> TrackBuilder<'a, track_state::SetAudioBlob<S>> {
        self._fields.0 = Option::Some(value.into());
        TrackBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

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

impl<'a, S> TrackBuilder<'a, S>
where
    S: track_state::State,
    S::EncryptedContentIv: track_state::IsUnset,
{
    /// Set the `encryptedContentIv` field (required)
    pub fn encrypted_content_iv(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> TrackBuilder<'a, track_state::SetEncryptedContentIv<S>> {
        self._fields.2 = Option::Some(value.into());
        TrackBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: track_state::State> TrackBuilder<'a, S> {
    /// Set the `encryptionAlgorithm` field (optional)
    pub fn encryption_algorithm(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `encryptionAlgorithm` field to an Option value (optional)
    pub fn maybe_encryption_algorithm(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<'a, S> TrackBuilder<'a, S>
where
    S: track_state::State,
    S::Title: track_state::IsUnset,
{
    /// Set the `title` field (required)
    pub fn title(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> TrackBuilder<'a, track_state::SetTitle<S>> {
        self._fields.4 = Option::Some(value.into());
        TrackBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> TrackBuilder<'a, S>
where
    S: track_state::State,
    S::EncryptedContentIv: track_state::IsSet,
    S::CreatedAt: track_state::IsSet,
    S::Title: track_state::IsSet,
    S::AudioBlob: track_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Track<'a> {
        Track {
            audio_blob: self._fields.0.unwrap(),
            created_at: self._fields.1.unwrap(),
            encrypted_content_iv: self._fields.2.unwrap(),
            encryption_algorithm: self
                ._fields
                .3
                .or_else(|| Some(CowStr::from("AES-GCM-256"))),
            title: 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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Track<'a> {
        Track {
            audio_blob: self._fields.0.unwrap(),
            created_at: self._fields.1.unwrap(),
            encrypted_content_iv: self._fields.2.unwrap(),
            encryption_algorithm: self
                ._fields
                .3
                .or_else(|| Some(CowStr::from("AES-GCM-256"))),
            title: self._fields.4.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_ch_indiemusi_alpha_track() -> 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.track"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "An encrypted audio track. The audio blob is encrypted with AES-GCM-256, and the decryption key is wrapped and stored in grant records.",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("title"),
                                SmolStr::new_static("audioBlob"),
                                SmolStr::new_static("encryptedContentIv"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("audioBlob"),
                                LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Timestamp when the track was uploaded"),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("encryptedContentIv"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Base64-encoded IV (12 bytes) used to encrypt the audio with the content key",
                                        ),
                                    ),
                                    max_length: Some(32usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("encryptionAlgorithm"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The symmetric algorithm used to encrypt the audio blob",
                                        ),
                                    ),
                                    max_length: Some(50usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("title"),
                                LexObjectProperty::String(LexString {
                                    description: Some(CowStr::new_static("Track title")),
                                    max_length: Some(255usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}