// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: app.beaconbits.bookmark.item
//
// 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::collection::{Collection, RecordError};
use jacquard_common::types::string::{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::community_lexicon::location::address::Address;
use crate::community_lexicon::location::geo::Geo;
/// A saved venue bookmark

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Item<'a> {
    ///Structured address using community lexicon
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub address_details: Option<Address<'a>>,
    ///Timestamp when the bookmark was created
    pub created_at: Datetime,
    ///Reference to a bookmark folder
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub folder_uri: Option<AtUri<'a>>,
    ///Structured location using community lexicon
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub location: Option<Geo<'a>>,
    ///User notes about the bookmark
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub notes: Option<CowStr<'a>>,
    ///Human-readable address
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub venue_address: Option<CowStr<'a>>,
    ///Category classification
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub venue_category: Option<CowStr<'a>>,
    ///Display name of the venue
    #[serde(borrow)]
    pub venue_name: CowStr<'a>,
    ///URI identifier for the venue (typically OSM URI)
    #[serde(borrow)]
    pub venue_uri: 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 ItemGetRecordOutput<'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: Item<'a>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct ItemRecord;
impl XrpcResp for ItemRecord {
    const NSID: &'static str = "app.beaconbits.bookmark.item";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = ItemGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Item<'_> {
    const NSID: &'static str = "app.beaconbits.bookmark.item";
    type Record = ItemRecord;
}

impl Collection for ItemRecord {
    const NSID: &'static str = "app.beaconbits.bookmark.item";
    type Record = ItemRecord;
}

impl<'a> LexiconSchema for Item<'a> {
    fn nsid() -> &'static str {
        "app.beaconbits.bookmark.item"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_beaconbits_bookmark_item()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.notes {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 280usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("notes"),
                        max: 280usize,
                        actual: count,
                    });
                }
            }
        }
        if let Some(ref value) = self.venue_address {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 256usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("venue_address"),
                        max: 256usize,
                        actual: count,
                    });
                }
            }
        }
        if let Some(ref value) = self.venue_category {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 64usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("venue_category"),
                        max: 64usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let value = &self.venue_name;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 128usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("venue_name"),
                        max: 128usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let value = &self.venue_uri;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 512usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("venue_uri"),
                        max: 512usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

pub mod item_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 VenueUri;
        type VenueName;
        type CreatedAt;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type VenueUri = Unset;
        type VenueName = Unset;
        type CreatedAt = Unset;
    }
    ///State transition - sets the `venue_uri` field to Set
    pub struct SetVenueUri<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetVenueUri<S> {}
    impl<S: State> State for SetVenueUri<S> {
        type VenueUri = Set<members::venue_uri>;
        type VenueName = S::VenueName;
        type CreatedAt = S::CreatedAt;
    }
    ///State transition - sets the `venue_name` field to Set
    pub struct SetVenueName<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetVenueName<S> {}
    impl<S: State> State for SetVenueName<S> {
        type VenueUri = S::VenueUri;
        type VenueName = Set<members::venue_name>;
        type CreatedAt = S::CreatedAt;
    }
    ///State transition - sets the `created_at` field to Set
    pub struct SetCreatedAt<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetCreatedAt<S> {}
    impl<S: State> State for SetCreatedAt<S> {
        type VenueUri = S::VenueUri;
        type VenueName = S::VenueName;
        type CreatedAt = Set<members::created_at>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `venue_uri` field
        pub struct venue_uri(());
        ///Marker type for the `venue_name` field
        pub struct venue_name(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
    }
}

/// Builder for constructing an instance of this type
pub struct ItemBuilder<'a, S: item_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Address<'a>>,
        Option<Datetime>,
        Option<AtUri<'a>>,
        Option<Geo<'a>>,
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Item<'a> {
    /// Create a new builder for this type
    pub fn new() -> ItemBuilder<'a, item_state::Empty> {
        ItemBuilder::new()
    }
}

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

impl<'a, S: item_state::State> ItemBuilder<'a, S> {
    /// Set the `addressDetails` field (optional)
    pub fn address_details(mut self, value: impl Into<Option<Address<'a>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `addressDetails` field to an Option value (optional)
    pub fn maybe_address_details(mut self, value: Option<Address<'a>>) -> Self {
        self._fields.0 = value;
        self
    }
}

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

impl<'a, S: item_state::State> ItemBuilder<'a, S> {
    /// Set the `folderUri` field (optional)
    pub fn folder_uri(mut self, value: impl Into<Option<AtUri<'a>>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `folderUri` field to an Option value (optional)
    pub fn maybe_folder_uri(mut self, value: Option<AtUri<'a>>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<'a, S: item_state::State> ItemBuilder<'a, S> {
    /// Set the `location` field (optional)
    pub fn location(mut self, value: impl Into<Option<Geo<'a>>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `location` field to an Option value (optional)
    pub fn maybe_location(mut self, value: Option<Geo<'a>>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<'a, S: item_state::State> ItemBuilder<'a, S> {
    /// Set the `notes` field (optional)
    pub fn notes(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `notes` field to an Option value (optional)
    pub fn maybe_notes(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<'a, S: item_state::State> ItemBuilder<'a, S> {
    /// Set the `venueAddress` field (optional)
    pub fn venue_address(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `venueAddress` field to an Option value (optional)
    pub fn maybe_venue_address(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<'a, S: item_state::State> ItemBuilder<'a, S> {
    /// Set the `venueCategory` field (optional)
    pub fn venue_category(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.6 = value.into();
        self
    }
    /// Set the `venueCategory` field to an Option value (optional)
    pub fn maybe_venue_category(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.6 = value;
        self
    }
}

impl<'a, S> ItemBuilder<'a, S>
where
    S: item_state::State,
    S::VenueName: item_state::IsUnset,
{
    /// Set the `venueName` field (required)
    pub fn venue_name(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> ItemBuilder<'a, item_state::SetVenueName<S>> {
        self._fields.7 = Option::Some(value.into());
        ItemBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> ItemBuilder<'a, S>
where
    S: item_state::State,
    S::VenueUri: item_state::IsUnset,
{
    /// Set the `venueUri` field (required)
    pub fn venue_uri(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> ItemBuilder<'a, item_state::SetVenueUri<S>> {
        self._fields.8 = Option::Some(value.into());
        ItemBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> ItemBuilder<'a, S>
where
    S: item_state::State,
    S::VenueUri: item_state::IsSet,
    S::VenueName: item_state::IsSet,
    S::CreatedAt: item_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Item<'a> {
        Item {
            address_details: self._fields.0,
            created_at: self._fields.1.unwrap(),
            folder_uri: self._fields.2,
            location: self._fields.3,
            notes: self._fields.4,
            venue_address: self._fields.5,
            venue_category: self._fields.6,
            venue_name: self._fields.7.unwrap(),
            venue_uri: self._fields.8.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>,
        >,
    ) -> Item<'a> {
        Item {
            address_details: self._fields.0,
            created_at: self._fields.1.unwrap(),
            folder_uri: self._fields.2,
            location: self._fields.3,
            notes: self._fields.4,
            venue_address: self._fields.5,
            venue_category: self._fields.6,
            venue_name: self._fields.7.unwrap(),
            venue_uri: self._fields.8.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_app_beaconbits_bookmark_item() -> 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("app.beaconbits.bookmark.item"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(CowStr::new_static("A saved venue bookmark")),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("venueUri"),
                                SmolStr::new_static("venueName"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("addressDetails"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static(
                                        "community.lexicon.location.address",
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Timestamp when the bookmark was created",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("folderUri"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Reference to a bookmark folder"),
                                    ),
                                    format: Some(LexStringFormat::AtUri),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("location"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("community.lexicon.location.geo"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("notes"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("User notes about the bookmark"),
                                    ),
                                    max_graphemes: Some(280usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("venueAddress"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Human-readable address"),
                                    ),
                                    max_graphemes: Some(256usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("venueCategory"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Category classification"),
                                    ),
                                    max_graphemes: Some(64usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("venueName"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Display name of the venue"),
                                    ),
                                    max_graphemes: Some(128usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("venueUri"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "URI identifier for the venue (typically OSM URI)",
                                        ),
                                    ),
                                    max_graphemes: Some(512usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}