// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: dev.tsunagite.song
//
// 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};
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 song included in a game hosting leaderboards via Tsunagite.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Song<'a> {
    ///The name of the composer of this song. Translations will typically be listed alongside the default.
    #[serde(borrow)]
    pub composer: Data<'a>,
    ///The game(s) this song is included in.
    #[serde(borrow)]
    pub game: Vec<AtUri<'a>>,
    ///The genre this song belongs to.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub genre: Option<Data<'a>>,
    ///The jacket or banner art of this song, for display in UI.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub jacket: Option<BlobRef<'a>>,
    ///The name of the jacket artist for this song.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub jacket_artist: Option<Data<'a>>,
    ///The source this song is from - an album, competition, other game, etc.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub source: Option<Data<'a>>,
    ///The human-readable subtitle of this song.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub subtitle: Option<Data<'a>>,
    ///The human-readable title of this song in UI. Translations will typically be listed alongside the default.
    #[serde(borrow)]
    pub title: Data<'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 SongGetRecordOutput<'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: Song<'a>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct SongRecord;
impl XrpcResp for SongRecord {
    const NSID: &'static str = "dev.tsunagite.song";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = SongGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Song<'_> {
    const NSID: &'static str = "dev.tsunagite.song";
    type Record = SongRecord;
}

impl Collection for SongRecord {
    const NSID: &'static str = "dev.tsunagite.song";
    type Record = SongRecord;
}

impl<'a> LexiconSchema for Song<'a> {
    fn nsid() -> &'static str {
        "dev.tsunagite.song"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_dev_tsunagite_song()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.jacket {
            {
                let size = value.blob().size;
                if size > 8000000usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("jacket"),
                        max: 8000000usize,
                        actual: size,
                    });
                }
            }
        }
        if let Some(ref value) = self.jacket {
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &[
                    "image/png",
                    "image/jpeg",
                    "image/jxl",
                    "image/webp",
                ];
                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("jacket"),
                        accepted: vec![
                            "image/png".to_string(), "image/jpeg".to_string(),
                            "image/jxl".to_string(), "image/webp".to_string()
                        ],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        Ok(())
    }
}

pub mod song_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 Game;
        type Title;
        type Composer;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Game = Unset;
        type Title = Unset;
        type Composer = Unset;
    }
    ///State transition - sets the `game` field to Set
    pub struct SetGame<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetGame<S> {}
    impl<S: State> State for SetGame<S> {
        type Game = Set<members::game>;
        type Title = S::Title;
        type Composer = S::Composer;
    }
    ///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 Game = S::Game;
        type Title = Set<members::title>;
        type Composer = S::Composer;
    }
    ///State transition - sets the `composer` field to Set
    pub struct SetComposer<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetComposer<S> {}
    impl<S: State> State for SetComposer<S> {
        type Game = S::Game;
        type Title = S::Title;
        type Composer = Set<members::composer>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `game` field
        pub struct game(());
        ///Marker type for the `title` field
        pub struct title(());
        ///Marker type for the `composer` field
        pub struct composer(());
    }
}

/// Builder for constructing an instance of this type
pub struct SongBuilder<'a, S: song_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Data<'a>>,
        Option<Vec<AtUri<'a>>>,
        Option<Data<'a>>,
        Option<BlobRef<'a>>,
        Option<Data<'a>>,
        Option<Data<'a>>,
        Option<Data<'a>>,
        Option<Data<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Song<'a> {
    /// Create a new builder for this type
    pub fn new() -> SongBuilder<'a, song_state::Empty> {
        SongBuilder::new()
    }
}

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

impl<'a, S> SongBuilder<'a, S>
where
    S: song_state::State,
    S::Composer: song_state::IsUnset,
{
    /// Set the `composer` field (required)
    pub fn composer(
        mut self,
        value: impl Into<Data<'a>>,
    ) -> SongBuilder<'a, song_state::SetComposer<S>> {
        self._fields.0 = Option::Some(value.into());
        SongBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> SongBuilder<'a, S>
where
    S: song_state::State,
    S::Game: song_state::IsUnset,
{
    /// Set the `game` field (required)
    pub fn game(
        mut self,
        value: impl Into<Vec<AtUri<'a>>>,
    ) -> SongBuilder<'a, song_state::SetGame<S>> {
        self._fields.1 = Option::Some(value.into());
        SongBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: song_state::State> SongBuilder<'a, S> {
    /// Set the `genre` field (optional)
    pub fn genre(mut self, value: impl Into<Option<Data<'a>>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `genre` field to an Option value (optional)
    pub fn maybe_genre(mut self, value: Option<Data<'a>>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<'a, S: song_state::State> SongBuilder<'a, S> {
    /// Set the `jacket` field (optional)
    pub fn jacket(mut self, value: impl Into<Option<BlobRef<'a>>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `jacket` field to an Option value (optional)
    pub fn maybe_jacket(mut self, value: Option<BlobRef<'a>>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<'a, S: song_state::State> SongBuilder<'a, S> {
    /// Set the `jacketArtist` field (optional)
    pub fn jacket_artist(mut self, value: impl Into<Option<Data<'a>>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `jacketArtist` field to an Option value (optional)
    pub fn maybe_jacket_artist(mut self, value: Option<Data<'a>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<'a, S: song_state::State> SongBuilder<'a, S> {
    /// Set the `source` field (optional)
    pub fn source(mut self, value: impl Into<Option<Data<'a>>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `source` field to an Option value (optional)
    pub fn maybe_source(mut self, value: Option<Data<'a>>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<'a, S: song_state::State> SongBuilder<'a, S> {
    /// Set the `subtitle` field (optional)
    pub fn subtitle(mut self, value: impl Into<Option<Data<'a>>>) -> Self {
        self._fields.6 = value.into();
        self
    }
    /// Set the `subtitle` field to an Option value (optional)
    pub fn maybe_subtitle(mut self, value: Option<Data<'a>>) -> Self {
        self._fields.6 = value;
        self
    }
}

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

impl<'a, S> SongBuilder<'a, S>
where
    S: song_state::State,
    S::Game: song_state::IsSet,
    S::Title: song_state::IsSet,
    S::Composer: song_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Song<'a> {
        Song {
            composer: self._fields.0.unwrap(),
            game: self._fields.1.unwrap(),
            genre: self._fields.2,
            jacket: self._fields.3,
            jacket_artist: self._fields.4,
            source: self._fields.5,
            subtitle: self._fields.6,
            title: self._fields.7.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, Data<'a>>,
    ) -> Song<'a> {
        Song {
            composer: self._fields.0.unwrap(),
            game: self._fields.1.unwrap(),
            genre: self._fields.2,
            jacket: self._fields.3,
            jacket_artist: self._fields.4,
            source: self._fields.5,
            subtitle: self._fields.6,
            title: self._fields.7.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_dev_tsunagite_song() -> 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("dev.tsunagite.song"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A song included in a game hosting leaderboards via Tsunagite.",
                        ),
                    ),
                    key: Some(CowStr::new_static("any")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("game"), SmolStr::new_static("title"),
                                SmolStr::new_static("composer")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("composer"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("dev.tsunagite.translatable"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("game"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static("The game(s) this song is included in."),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        description: Some(
                                            CowStr::new_static(
                                                "All URIs must point to records of type `dev.tsunagite.game`.",
                                            ),
                                        ),
                                        format: Some(LexStringFormat::AtUri),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("genre"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("dev.tsunagite.translatable"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("jacket"),
                                LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                            );
                            map.insert(
                                SmolStr::new_static("jacketArtist"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("dev.tsunagite.translatable"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("source"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("dev.tsunagite.translatable"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("subtitle"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("dev.tsunagite.translatable"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("title"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("dev.tsunagite.translatable"),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}