// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: ch.indiemusi.alpha.release
//
// 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::{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};
use crate::ch_indiemusi::alpha::recording::Recording;
use crate::ch_indiemusi::alpha::actor::artist;
use crate::ch_indiemusi::alpha::release;
/// Information about an artist contributing to the release

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct Artist<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub artist: Option<artist::Artist<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub did: Option<Did<'a>>,
    #[serde(borrow)]
    pub name: CowStr<'a>,
}

/// A release (album, EP, single) containing recordings of songs or musical works

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Release<'a> {
    #[serde(borrow)]
    pub artists: Vec<release::Artist<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub artwork_image: Option<BlobRef<'a>>,
    ///GTIN (Global Trade Item Number) with which the release is registered, e.g. EAN or UPC
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub gtin: Option<CowStr<'a>>,
    ///List of recordings (ch.indiemusi.alpha.recording) included in this release
    #[serde(borrow)]
    pub recordings: Vec<Recording<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub release_date: Option<Datetime>,
    #[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 ReleaseGetRecordOutput<'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: Release<'a>,
}

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

impl<'a> LexiconSchema for Artist<'a> {
    fn nsid() -> &'static str {
        "ch.indiemusi.alpha.release"
    }
    fn def_name() -> &'static str {
        "artist"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_ch_indiemusi_alpha_release()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.name;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 255usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("name"),
                    max: 255usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

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

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

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

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

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

impl<'a> LexiconSchema for Release<'a> {
    fn nsid() -> &'static str {
        "ch.indiemusi.alpha.release"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_ch_indiemusi_alpha_release()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.artists;
            #[allow(unused_comparisons)]
            if value.len() < 1usize {
                return Err(ConstraintError::MinLength {
                    path: ValidationPath::from_field("artists"),
                    min: 1usize,
                    actual: value.len(),
                });
            }
        }
        if let Some(ref value) = self.gtin {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 14usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("gtin"),
                    max: 14usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.recordings;
            #[allow(unused_comparisons)]
            if value.len() < 1usize {
                return Err(ConstraintError::MinLength {
                    path: ValidationPath::from_field("recordings"),
                    min: 1usize,
                    actual: value.len(),
                });
            }
        }
        {
            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 lexicon_doc_ch_indiemusi_alpha_release() -> 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.release"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("artist"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "Information about an artist contributing to the release",
                        ),
                    ),
                    required: Some(vec![SmolStr::new_static("name")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("artist"),
                            LexObjectProperty::Ref(LexRef {
                                r#ref: CowStr::new_static(
                                    "ch.indiemusi.alpha.actor.artist",
                                ),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("did"),
                            LexObjectProperty::String(LexString {
                                format: Some(LexStringFormat::Did),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("name"),
                            LexObjectProperty::String(LexString {
                                max_length: Some(255usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A release (album, EP, single) containing recordings of songs or musical works",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("title"),
                                SmolStr::new_static("artists"),
                                SmolStr::new_static("recordings")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("artists"),
                                LexObjectProperty::Array(LexArray {
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#artist"),
                                        ..Default::default()
                                    }),
                                    min_length: Some(1usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("artworkImage"),
                                LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                            );
                            map.insert(
                                SmolStr::new_static("gtin"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "GTIN (Global Trade Item Number) with which the release is registered, e.g. EAN or UPC",
                                        ),
                                    ),
                                    max_length: Some(14usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("recordings"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "List of recordings (ch.indiemusi.alpha.recording) included in this release",
                                        ),
                                    ),
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("ch.indiemusi.alpha.recording"),
                                        ..Default::default()
                                    }),
                                    min_length: Some(1usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("releaseDate"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("title"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(255usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod release_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 Title;
        type Artists;
        type Recordings;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Title = Unset;
        type Artists = Unset;
        type Recordings = Unset;
    }
    ///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 Title = Set<members::title>;
        type Artists = S::Artists;
        type Recordings = S::Recordings;
    }
    ///State transition - sets the `artists` field to Set
    pub struct SetArtists<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetArtists<S> {}
    impl<S: State> State for SetArtists<S> {
        type Title = S::Title;
        type Artists = Set<members::artists>;
        type Recordings = S::Recordings;
    }
    ///State transition - sets the `recordings` field to Set
    pub struct SetRecordings<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetRecordings<S> {}
    impl<S: State> State for SetRecordings<S> {
        type Title = S::Title;
        type Artists = S::Artists;
        type Recordings = Set<members::recordings>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `title` field
        pub struct title(());
        ///Marker type for the `artists` field
        pub struct artists(());
        ///Marker type for the `recordings` field
        pub struct recordings(());
    }
}

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

impl<'a> Release<'a> {
    /// Create a new builder for this type
    pub fn new() -> ReleaseBuilder<'a, release_state::Empty> {
        ReleaseBuilder::new()
    }
}

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

impl<'a, S> ReleaseBuilder<'a, S>
where
    S: release_state::State,
    S::Artists: release_state::IsUnset,
{
    /// Set the `artists` field (required)
    pub fn artists(
        mut self,
        value: impl Into<Vec<release::Artist<'a>>>,
    ) -> ReleaseBuilder<'a, release_state::SetArtists<S>> {
        self._fields.0 = Option::Some(value.into());
        ReleaseBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: release_state::State> ReleaseBuilder<'a, S> {
    /// Set the `artworkImage` field (optional)
    pub fn artwork_image(mut self, value: impl Into<Option<BlobRef<'a>>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `artworkImage` field to an Option value (optional)
    pub fn maybe_artwork_image(mut self, value: Option<BlobRef<'a>>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<'a, S: release_state::State> ReleaseBuilder<'a, S> {
    /// Set the `gtin` field (optional)
    pub fn gtin(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `gtin` field to an Option value (optional)
    pub fn maybe_gtin(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<'a, S> ReleaseBuilder<'a, S>
where
    S: release_state::State,
    S::Recordings: release_state::IsUnset,
{
    /// Set the `recordings` field (required)
    pub fn recordings(
        mut self,
        value: impl Into<Vec<Recording<'a>>>,
    ) -> ReleaseBuilder<'a, release_state::SetRecordings<S>> {
        self._fields.3 = Option::Some(value.into());
        ReleaseBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: release_state::State> ReleaseBuilder<'a, S> {
    /// Set the `releaseDate` field (optional)
    pub fn release_date(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `releaseDate` field to an Option value (optional)
    pub fn maybe_release_date(mut self, value: Option<Datetime>) -> Self {
        self._fields.4 = value;
        self
    }
}

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

impl<'a, S> ReleaseBuilder<'a, S>
where
    S: release_state::State,
    S::Title: release_state::IsSet,
    S::Artists: release_state::IsSet,
    S::Recordings: release_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Release<'a> {
        Release {
            artists: self._fields.0.unwrap(),
            artwork_image: self._fields.1,
            gtin: self._fields.2,
            recordings: self._fields.3.unwrap(),
            release_date: self._fields.4,
            title: self._fields.5.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>,
        >,
    ) -> Release<'a> {
        Release {
            artists: self._fields.0.unwrap(),
            artwork_image: self._fields.1,
            gtin: self._fields.2,
            recordings: self._fields.3.unwrap(),
            release_date: self._fields.4,
            title: self._fields.5.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}