// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: org.passingreads.book.registration
//
// 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;
use jacquard_common::deps::bytes::Bytes;

#[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::org_passingreads::AspectRatio;
/// A book that has been registered on PassingReads

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Registration<'a> {
    ///Aspect ratio of the cover image
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub aspect_ratio: Option<AspectRatio<'a>>,
    ///Authors of this book, in order of credit. An empty array implies a book of anonymous or unknown authorship.
    #[serde(borrow)]
    pub authors: Vec<CowStr<'a>>,
    ///The book's ID (as defined on its QR Code)
    #[serde(borrow)]
    pub book_id: CowStr<'a>,
    ///The MultiFormat public key of the book.
    #[serde(with = "jacquard_common::serde_bytes_helper")]
    pub book_pub: Bytes,
    ///The MultiFormat signature of this record, without this attribute, as created by the private key associated with the book.
    #[serde(with = "jacquard_common::serde_bytes_helper")]
    pub book_sig: Bytes,
    ///Cover image of the book
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub cover: Option<BlobRef<'a>>,
    ///The DID of the person who registered the book. Included here, so it's verifiable with the bookSig.
    #[serde(borrow)]
    pub did: Did<'a>,
    pub occurred_at: Datetime,
    ///The book's Open Library Edition ID
    #[serde(borrow)]
    pub publication_id: CowStr<'a>,
    ///The title of the book
    #[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 RegistrationGetRecordOutput<'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: Registration<'a>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct RegistrationRecord;
impl XrpcResp for RegistrationRecord {
    const NSID: &'static str = "org.passingreads.book.registration";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = RegistrationGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Registration<'_> {
    const NSID: &'static str = "org.passingreads.book.registration";
    type Record = RegistrationRecord;
}

impl Collection for RegistrationRecord {
    const NSID: &'static str = "org.passingreads.book.registration";
    type Record = RegistrationRecord;
}

impl<'a> LexiconSchema for Registration<'a> {
    fn nsid() -> &'static str {
        "org.passingreads.book.registration"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_org_passingreads_book_registration()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.cover {
            {
                let size = value.blob().size;
                if size > 1000000usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("cover"),
                        max: 1000000usize,
                        actual: size,
                    });
                }
            }
        }
        if let Some(ref value) = self.cover {
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &["image/png", "image/jpeg"];
                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("cover"),
                        accepted: vec![
                            "image/png".to_string(), "image/jpeg".to_string()
                        ],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        {
            let value = &self.title;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 512usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("title"),
                    max: 512usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.title;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) < 1usize {
                return Err(ConstraintError::MinLength {
                    path: ValidationPath::from_field("title"),
                    min: 1usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod registration_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 BookPub;
        type Did;
        type BookId;
        type Authors;
        type Title;
        type PublicationId;
        type OccurredAt;
        type BookSig;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type BookPub = Unset;
        type Did = Unset;
        type BookId = Unset;
        type Authors = Unset;
        type Title = Unset;
        type PublicationId = Unset;
        type OccurredAt = Unset;
        type BookSig = Unset;
    }
    ///State transition - sets the `book_pub` field to Set
    pub struct SetBookPub<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetBookPub<S> {}
    impl<S: State> State for SetBookPub<S> {
        type BookPub = Set<members::book_pub>;
        type Did = S::Did;
        type BookId = S::BookId;
        type Authors = S::Authors;
        type Title = S::Title;
        type PublicationId = S::PublicationId;
        type OccurredAt = S::OccurredAt;
        type BookSig = S::BookSig;
    }
    ///State transition - sets the `did` field to Set
    pub struct SetDid<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetDid<S> {}
    impl<S: State> State for SetDid<S> {
        type BookPub = S::BookPub;
        type Did = Set<members::did>;
        type BookId = S::BookId;
        type Authors = S::Authors;
        type Title = S::Title;
        type PublicationId = S::PublicationId;
        type OccurredAt = S::OccurredAt;
        type BookSig = S::BookSig;
    }
    ///State transition - sets the `book_id` field to Set
    pub struct SetBookId<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetBookId<S> {}
    impl<S: State> State for SetBookId<S> {
        type BookPub = S::BookPub;
        type Did = S::Did;
        type BookId = Set<members::book_id>;
        type Authors = S::Authors;
        type Title = S::Title;
        type PublicationId = S::PublicationId;
        type OccurredAt = S::OccurredAt;
        type BookSig = S::BookSig;
    }
    ///State transition - sets the `authors` field to Set
    pub struct SetAuthors<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetAuthors<S> {}
    impl<S: State> State for SetAuthors<S> {
        type BookPub = S::BookPub;
        type Did = S::Did;
        type BookId = S::BookId;
        type Authors = Set<members::authors>;
        type Title = S::Title;
        type PublicationId = S::PublicationId;
        type OccurredAt = S::OccurredAt;
        type BookSig = S::BookSig;
    }
    ///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 BookPub = S::BookPub;
        type Did = S::Did;
        type BookId = S::BookId;
        type Authors = S::Authors;
        type Title = Set<members::title>;
        type PublicationId = S::PublicationId;
        type OccurredAt = S::OccurredAt;
        type BookSig = S::BookSig;
    }
    ///State transition - sets the `publication_id` field to Set
    pub struct SetPublicationId<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetPublicationId<S> {}
    impl<S: State> State for SetPublicationId<S> {
        type BookPub = S::BookPub;
        type Did = S::Did;
        type BookId = S::BookId;
        type Authors = S::Authors;
        type Title = S::Title;
        type PublicationId = Set<members::publication_id>;
        type OccurredAt = S::OccurredAt;
        type BookSig = S::BookSig;
    }
    ///State transition - sets the `occurred_at` field to Set
    pub struct SetOccurredAt<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetOccurredAt<S> {}
    impl<S: State> State for SetOccurredAt<S> {
        type BookPub = S::BookPub;
        type Did = S::Did;
        type BookId = S::BookId;
        type Authors = S::Authors;
        type Title = S::Title;
        type PublicationId = S::PublicationId;
        type OccurredAt = Set<members::occurred_at>;
        type BookSig = S::BookSig;
    }
    ///State transition - sets the `book_sig` field to Set
    pub struct SetBookSig<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetBookSig<S> {}
    impl<S: State> State for SetBookSig<S> {
        type BookPub = S::BookPub;
        type Did = S::Did;
        type BookId = S::BookId;
        type Authors = S::Authors;
        type Title = S::Title;
        type PublicationId = S::PublicationId;
        type OccurredAt = S::OccurredAt;
        type BookSig = Set<members::book_sig>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `book_pub` field
        pub struct book_pub(());
        ///Marker type for the `did` field
        pub struct did(());
        ///Marker type for the `book_id` field
        pub struct book_id(());
        ///Marker type for the `authors` field
        pub struct authors(());
        ///Marker type for the `title` field
        pub struct title(());
        ///Marker type for the `publication_id` field
        pub struct publication_id(());
        ///Marker type for the `occurred_at` field
        pub struct occurred_at(());
        ///Marker type for the `book_sig` field
        pub struct book_sig(());
    }
}

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

impl<'a> Registration<'a> {
    /// Create a new builder for this type
    pub fn new() -> RegistrationBuilder<'a, registration_state::Empty> {
        RegistrationBuilder::new()
    }
}

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

impl<'a, S: registration_state::State> RegistrationBuilder<'a, S> {
    /// Set the `aspectRatio` field (optional)
    pub fn aspect_ratio(mut self, value: impl Into<Option<AspectRatio<'a>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `aspectRatio` field to an Option value (optional)
    pub fn maybe_aspect_ratio(mut self, value: Option<AspectRatio<'a>>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<'a, S> RegistrationBuilder<'a, S>
where
    S: registration_state::State,
    S::Authors: registration_state::IsUnset,
{
    /// Set the `authors` field (required)
    pub fn authors(
        mut self,
        value: impl Into<Vec<CowStr<'a>>>,
    ) -> RegistrationBuilder<'a, registration_state::SetAuthors<S>> {
        self._fields.1 = Option::Some(value.into());
        RegistrationBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> RegistrationBuilder<'a, S>
where
    S: registration_state::State,
    S::BookId: registration_state::IsUnset,
{
    /// Set the `bookId` field (required)
    pub fn book_id(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> RegistrationBuilder<'a, registration_state::SetBookId<S>> {
        self._fields.2 = Option::Some(value.into());
        RegistrationBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> RegistrationBuilder<'a, S>
where
    S: registration_state::State,
    S::BookPub: registration_state::IsUnset,
{
    /// Set the `bookPub` field (required)
    pub fn book_pub(
        mut self,
        value: impl Into<Bytes>,
    ) -> RegistrationBuilder<'a, registration_state::SetBookPub<S>> {
        self._fields.3 = Option::Some(value.into());
        RegistrationBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> RegistrationBuilder<'a, S>
where
    S: registration_state::State,
    S::BookSig: registration_state::IsUnset,
{
    /// Set the `bookSig` field (required)
    pub fn book_sig(
        mut self,
        value: impl Into<Bytes>,
    ) -> RegistrationBuilder<'a, registration_state::SetBookSig<S>> {
        self._fields.4 = Option::Some(value.into());
        RegistrationBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: registration_state::State> RegistrationBuilder<'a, S> {
    /// Set the `cover` field (optional)
    pub fn cover(mut self, value: impl Into<Option<BlobRef<'a>>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `cover` field to an Option value (optional)
    pub fn maybe_cover(mut self, value: Option<BlobRef<'a>>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<'a, S> RegistrationBuilder<'a, S>
where
    S: registration_state::State,
    S::Did: registration_state::IsUnset,
{
    /// Set the `did` field (required)
    pub fn did(
        mut self,
        value: impl Into<Did<'a>>,
    ) -> RegistrationBuilder<'a, registration_state::SetDid<S>> {
        self._fields.6 = Option::Some(value.into());
        RegistrationBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> RegistrationBuilder<'a, S>
where
    S: registration_state::State,
    S::OccurredAt: registration_state::IsUnset,
{
    /// Set the `occurredAt` field (required)
    pub fn occurred_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> RegistrationBuilder<'a, registration_state::SetOccurredAt<S>> {
        self._fields.7 = Option::Some(value.into());
        RegistrationBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> RegistrationBuilder<'a, S>
where
    S: registration_state::State,
    S::PublicationId: registration_state::IsUnset,
{
    /// Set the `publicationId` field (required)
    pub fn publication_id(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> RegistrationBuilder<'a, registration_state::SetPublicationId<S>> {
        self._fields.8 = Option::Some(value.into());
        RegistrationBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

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

impl<'a, S> RegistrationBuilder<'a, S>
where
    S: registration_state::State,
    S::BookPub: registration_state::IsSet,
    S::Did: registration_state::IsSet,
    S::BookId: registration_state::IsSet,
    S::Authors: registration_state::IsSet,
    S::Title: registration_state::IsSet,
    S::PublicationId: registration_state::IsSet,
    S::OccurredAt: registration_state::IsSet,
    S::BookSig: registration_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Registration<'a> {
        Registration {
            aspect_ratio: self._fields.0,
            authors: self._fields.1.unwrap(),
            book_id: self._fields.2.unwrap(),
            book_pub: self._fields.3.unwrap(),
            book_sig: self._fields.4.unwrap(),
            cover: self._fields.5,
            did: self._fields.6.unwrap(),
            occurred_at: self._fields.7.unwrap(),
            publication_id: self._fields.8.unwrap(),
            title: self._fields.9.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>,
        >,
    ) -> Registration<'a> {
        Registration {
            aspect_ratio: self._fields.0,
            authors: self._fields.1.unwrap(),
            book_id: self._fields.2.unwrap(),
            book_pub: self._fields.3.unwrap(),
            book_sig: self._fields.4.unwrap(),
            cover: self._fields.5,
            did: self._fields.6.unwrap(),
            occurred_at: self._fields.7.unwrap(),
            publication_id: self._fields.8.unwrap(),
            title: self._fields.9.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_org_passingreads_book_registration() -> 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("org.passingreads.book.registration"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A book that has been registered on PassingReads",
                        ),
                    ),
                    key: Some(CowStr::new_static("any")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("did"), SmolStr::new_static("bookId"),
                                SmolStr::new_static("title"),
                                SmolStr::new_static("authors"),
                                SmolStr::new_static("publicationId"),
                                SmolStr::new_static("occurredAt"),
                                SmolStr::new_static("bookPub"),
                                SmolStr::new_static("bookSig")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("aspectRatio"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static(
                                        "org.passingreads.defs#aspectRatio",
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("authors"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Authors of this book, in order of credit. An empty array implies a book of anonymous or unknown authorship.",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        min_length: Some(1usize),
                                        max_length: Some(512usize),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("bookId"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The book's ID (as defined on its QR Code)",
                                        ),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("bookPub"),
                                LexObjectProperty::Bytes(LexBytes { ..Default::default() }),
                            );
                            map.insert(
                                SmolStr::new_static("bookSig"),
                                LexObjectProperty::Bytes(LexBytes { ..Default::default() }),
                            );
                            map.insert(
                                SmolStr::new_static("cover"),
                                LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                            );
                            map.insert(
                                SmolStr::new_static("did"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The DID of the person who registered the book. Included here, so it's verifiable with the bookSig.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Did),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("occurredAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("publicationId"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("The book's Open Library Edition ID"),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("title"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("The title of the book"),
                                    ),
                                    min_length: Some(1usize),
                                    max_length: Some(512usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}