// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: org.passingreads.book.event
//
// 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::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, open_union};
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::com_atproto::repo::strong_ref::StrongRef;
use crate::community_lexicon::location::hthree::Hthree;
use crate::org_passingreads::book::event;
/// The status of a book has changed.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Event<'a> {
    ///The book that was dropped (a org.passingreads.book.registration)
    #[serde(borrow)]
    pub book: StrongRef<'a>,
    ///The multicodec public key of the book.
    #[serde(with = "jacquard_common::serde_bytes_helper")]
    pub book_pub: Bytes,
    ///The 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,
    ///The DID of the person who registered the book. Included here, so it's verifiable with the bookSig.
    #[serde(borrow)]
    pub did: Did<'a>,
    ///What event has occurred
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub event: Option<EventEvent<'a>>,
    ///Where this event occurred (an h3 cell, an OSM place, or a link to an outpost — org.passingreads.outpost.registration)
    #[serde(borrow)]
    pub location: EventLocation<'a>,
    ///Client-declared timestamp of when the book was dropped
    pub occurred_at: Datetime,
}

/// What event has occurred

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum EventEvent<'a> {
    OrgPassingreadsBookCheckin,
    OrgPassingreadsBookDrop,
    OrgPassingreadsBookFind,
    Other(CowStr<'a>),
}

impl<'a> EventEvent<'a> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::OrgPassingreadsBookCheckin => "org.passingreads.book.checkin",
            Self::OrgPassingreadsBookDrop => "org.passingreads.book.drop",
            Self::OrgPassingreadsBookFind => "org.passingreads.book.find",
            Self::Other(s) => s.as_ref(),
        }
    }
}

impl<'a> From<&'a str> for EventEvent<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "org.passingreads.book.checkin" => Self::OrgPassingreadsBookCheckin,
            "org.passingreads.book.drop" => Self::OrgPassingreadsBookDrop,
            "org.passingreads.book.find" => Self::OrgPassingreadsBookFind,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for EventEvent<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "org.passingreads.book.checkin" => Self::OrgPassingreadsBookCheckin,
            "org.passingreads.book.drop" => Self::OrgPassingreadsBookDrop,
            "org.passingreads.book.find" => Self::OrgPassingreadsBookFind,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> core::fmt::Display for EventEvent<'a> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl<'a> AsRef<str> for EventEvent<'a> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<'a> serde::Serialize for EventEvent<'a> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de, 'a> serde::Deserialize<'de> for EventEvent<'a>
where
    'de: 'a,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = <&'de str>::deserialize(deserializer)?;
        Ok(Self::from(s))
    }
}

impl<'a> Default for EventEvent<'a> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl jacquard_common::IntoStatic for EventEvent<'_> {
    type Output = EventEvent<'static>;
    fn into_static(self) -> Self::Output {
        match self {
            EventEvent::OrgPassingreadsBookCheckin => {
                EventEvent::OrgPassingreadsBookCheckin
            }
            EventEvent::OrgPassingreadsBookDrop => EventEvent::OrgPassingreadsBookDrop,
            EventEvent::OrgPassingreadsBookFind => EventEvent::OrgPassingreadsBookFind,
            EventEvent::Other(v) => EventEvent::Other(v.into_static()),
        }
    }
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type")]
#[serde(bound(deserialize = "'de: 'a"))]
pub enum EventLocation<'a> {
    #[serde(rename = "com.atproto.repo.strongRef#main")]
    StrongRef(Box<StrongRef<'a>>),
    #[serde(rename = "community.lexicon.location.hthree#main")]
    Hthree(Box<Hthree<'a>>),
    #[serde(rename = "org.passingreads.book.event#osmLocation")]
    OsmLocation(Box<event::OsmLocation<'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 EventGetRecordOutput<'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: Event<'a>,
}

/// A physical location from OpenStreetMap.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct OsmLocation<'a> {
    ///The type of place (e.g., cafe, library, park).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub category: Option<CowStr<'a>>,
    ///The name of the place from OpenStreetMap.
    #[serde(borrow)]
    pub name: CowStr<'a>,
    ///The OpenStreetMap element ID in interoperable format: N (node), W (way), or R (relation) prefix followed by numeric ID. Example: N123456789
    #[serde(borrow)]
    pub osm_id: CowStr<'a>,
    ///The H3 cell index for proximity queries.
    #[serde(borrow)]
    pub value: CowStr<'a>,
}

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

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

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

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

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

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

impl<'a> LexiconSchema for Event<'a> {
    fn nsid() -> &'static str {
        "org.passingreads.book.event"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_org_passingreads_book_event()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

impl<'a> LexiconSchema for OsmLocation<'a> {
    fn nsid() -> &'static str {
        "org.passingreads.book.event"
    }
    fn def_name() -> &'static str {
        "osmLocation"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_org_passingreads_book_event()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

pub mod event_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 OccurredAt;
        type Did;
        type Location;
        type BookPub;
        type Book;
        type BookSig;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type OccurredAt = Unset;
        type Did = Unset;
        type Location = Unset;
        type BookPub = Unset;
        type Book = Unset;
        type BookSig = Unset;
    }
    ///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 OccurredAt = Set<members::occurred_at>;
        type Did = S::Did;
        type Location = S::Location;
        type BookPub = S::BookPub;
        type Book = S::Book;
        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 OccurredAt = S::OccurredAt;
        type Did = Set<members::did>;
        type Location = S::Location;
        type BookPub = S::BookPub;
        type Book = S::Book;
        type BookSig = S::BookSig;
    }
    ///State transition - sets the `location` field to Set
    pub struct SetLocation<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetLocation<S> {}
    impl<S: State> State for SetLocation<S> {
        type OccurredAt = S::OccurredAt;
        type Did = S::Did;
        type Location = Set<members::location>;
        type BookPub = S::BookPub;
        type Book = S::Book;
        type BookSig = S::BookSig;
    }
    ///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 OccurredAt = S::OccurredAt;
        type Did = S::Did;
        type Location = S::Location;
        type BookPub = Set<members::book_pub>;
        type Book = S::Book;
        type BookSig = S::BookSig;
    }
    ///State transition - sets the `book` field to Set
    pub struct SetBook<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetBook<S> {}
    impl<S: State> State for SetBook<S> {
        type OccurredAt = S::OccurredAt;
        type Did = S::Did;
        type Location = S::Location;
        type BookPub = S::BookPub;
        type Book = Set<members::book>;
        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 OccurredAt = S::OccurredAt;
        type Did = S::Did;
        type Location = S::Location;
        type BookPub = S::BookPub;
        type Book = S::Book;
        type BookSig = Set<members::book_sig>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `occurred_at` field
        pub struct occurred_at(());
        ///Marker type for the `did` field
        pub struct did(());
        ///Marker type for the `location` field
        pub struct location(());
        ///Marker type for the `book_pub` field
        pub struct book_pub(());
        ///Marker type for the `book` field
        pub struct book(());
        ///Marker type for the `book_sig` field
        pub struct book_sig(());
    }
}

/// Builder for constructing an instance of this type
pub struct EventBuilder<'a, S: event_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<StrongRef<'a>>,
        Option<Bytes>,
        Option<Bytes>,
        Option<Did<'a>>,
        Option<EventEvent<'a>>,
        Option<EventLocation<'a>>,
        Option<Datetime>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Event<'a> {
    /// Create a new builder for this type
    pub fn new() -> EventBuilder<'a, event_state::Empty> {
        EventBuilder::new()
    }
}

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

impl<'a, S> EventBuilder<'a, S>
where
    S: event_state::State,
    S::Book: event_state::IsUnset,
{
    /// Set the `book` field (required)
    pub fn book(
        mut self,
        value: impl Into<StrongRef<'a>>,
    ) -> EventBuilder<'a, event_state::SetBook<S>> {
        self._fields.0 = Option::Some(value.into());
        EventBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

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

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

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

impl<'a, S: event_state::State> EventBuilder<'a, S> {
    /// Set the `event` field (optional)
    pub fn event(mut self, value: impl Into<Option<EventEvent<'a>>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `event` field to an Option value (optional)
    pub fn maybe_event(mut self, value: Option<EventEvent<'a>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<'a, S> EventBuilder<'a, S>
where
    S: event_state::State,
    S::Location: event_state::IsUnset,
{
    /// Set the `location` field (required)
    pub fn location(
        mut self,
        value: impl Into<EventLocation<'a>>,
    ) -> EventBuilder<'a, event_state::SetLocation<S>> {
        self._fields.5 = Option::Some(value.into());
        EventBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

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

impl<'a, S> EventBuilder<'a, S>
where
    S: event_state::State,
    S::OccurredAt: event_state::IsSet,
    S::Did: event_state::IsSet,
    S::Location: event_state::IsSet,
    S::BookPub: event_state::IsSet,
    S::Book: event_state::IsSet,
    S::BookSig: event_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Event<'a> {
        Event {
            book: self._fields.0.unwrap(),
            book_pub: self._fields.1.unwrap(),
            book_sig: self._fields.2.unwrap(),
            did: self._fields.3.unwrap(),
            event: self._fields.4,
            location: self._fields.5.unwrap(),
            occurred_at: self._fields.6.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>,
        >,
    ) -> Event<'a> {
        Event {
            book: self._fields.0.unwrap(),
            book_pub: self._fields.1.unwrap(),
            book_sig: self._fields.2.unwrap(),
            did: self._fields.3.unwrap(),
            event: self._fields.4,
            location: self._fields.5.unwrap(),
            occurred_at: self._fields.6.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_org_passingreads_book_event() -> 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.event"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static("The status of a book has changed."),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("did"), SmolStr::new_static("book"),
                                SmolStr::new_static("occurredAt"),
                                SmolStr::new_static("location"),
                                SmolStr::new_static("bookPub"),
                                SmolStr::new_static("bookSig")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("book"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static(
                                        "com.atproto.repo.strongRef#main",
                                    ),
                                    ..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("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("event"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("What event has occurred"),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("location"),
                                LexObjectProperty::Union(LexRefUnion {
                                    description: Some(
                                        CowStr::new_static(
                                            "Where this event occurred (an h3 cell, an OSM place, or a link to an outpost — org.passingreads.outpost.registration)",
                                        ),
                                    ),
                                    refs: vec![
                                        CowStr::new_static("com.atproto.repo.strongRef#main"),
                                        CowStr::new_static("community.lexicon.location.hthree#main"),
                                        CowStr::new_static("#osmLocation")
                                    ],
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("occurredAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Client-declared timestamp of when the book was dropped",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("osmLocation"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static("A physical location from OpenStreetMap."),
                    ),
                    required: Some(
                        vec![
                            SmolStr::new_static("osmId"), SmolStr::new_static("name"),
                            SmolStr::new_static("value")
                        ],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("category"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "The type of place (e.g., cafe, library, park).",
                                    ),
                                ),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("name"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "The name of the place from OpenStreetMap.",
                                    ),
                                ),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("osmId"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "The OpenStreetMap element ID in interoperable format: N (node), W (way), or R (relation) prefix followed by numeric ID. Example: N123456789",
                                    ),
                                ),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("value"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "The H3 cell index for proximity queries.",
                                    ),
                                ),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}