// @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, 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::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::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};
/// An encrypted audio track. The audio blob is encrypted with AES-GCM-256, and the decryption key is wrapped and stored in grant records.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "ch.indiemusi.alpha.track",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Track<S: BosStr = DefaultStr> {
    ///The encrypted audio file
    pub audio_blob: BlobRef<S>,
    ///Timestamp when the track was uploaded
    pub created_at: Datetime,
    ///Base64-encoded IV (12 bytes) used to encrypt the audio with the content key
    pub encrypted_content_iv: S,
    ///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")]
    pub encryption_algorithm: Option<S>,
    ///Track title
    pub title: 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 TrackGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Track<S>,
}

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

/// 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<S: BosStr> = TrackGetRecordOutput<S>;
    type Err = RecordError;
}

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

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

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

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

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

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

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

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

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

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

impl<St: track_state::State, S: BosStr> TrackBuilder<St, S> {
    /// Set the `encryptionAlgorithm` field (optional)
    pub fn encryption_algorithm(mut self, value: impl Into<Option<S>>) -> 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<S>) -> Self {
        self._fields.3 = value;
        self
    }
}

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

impl<St, S: BosStr> TrackBuilder<St, S>
where
    St: track_state::State,
    St::AudioBlob: track_state::IsSet,
    St::CreatedAt: track_state::IsSet,
    St::EncryptedContentIv: track_state::IsSet,
    St::Title: track_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Track<S> {
        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(S::from_static("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<SmolStr, Data<S>>) -> Track<S> {
        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(S::from_static("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()
    }
}