// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: app.openmkt.marketplace.listing
//
// 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, 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::app_openmkt::marketplace::listing;

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct LocationObj<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub county: Option<CowStr<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub locality: Option<CowStr<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub state: Option<CowStr<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub zip_prefix: Option<CowStr<'a>>,
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Listing<'a> {
    #[serde(borrow)]
    pub category: CowStr<'a>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub condition: Option<CowStr<'a>>,
    pub created_at: Datetime,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub description: Option<CowStr<'a>>,
    ///Optional external URL for purchasing the item (e.g., Amazon, eBay link)
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub external_url: Option<CowStr<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hide_from_friends: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub images: Option<Vec<BlobRef<'a>>>,
    #[serde(borrow)]
    pub location: listing::LocationObj<'a>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub metadata: Option<listing::MetadataObj<'a>>,
    ///String representation
    #[serde(borrow)]
    pub price: CowStr<'a>,
    #[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 ListingGetRecordOutput<'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: Listing<'a>,
}


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

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

impl<'a> LexiconSchema for LocationObj<'a> {
    fn nsid() -> &'static str {
        "app.openmkt.marketplace.listing"
    }
    fn def_name() -> &'static str {
        "locationObj"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_openmkt_marketplace_listing()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

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

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

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

impl Collection for Listing<'_> {
    const NSID: &'static str = "app.openmkt.marketplace.listing";
    type Record = ListingRecord;
}

impl Collection for ListingRecord {
    const NSID: &'static str = "app.openmkt.marketplace.listing";
    type Record = ListingRecord;
}

impl<'a> LexiconSchema for Listing<'a> {
    fn nsid() -> &'static str {
        "app.openmkt.marketplace.listing"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_openmkt_marketplace_listing()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.description {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 3000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("description"),
                    max: 3000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.external_url {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 2000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("external_url"),
                    max: 2000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.title;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 300usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("title"),
                    max: 300usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

impl<'a> LexiconSchema for MetadataObj<'a> {
    fn nsid() -> &'static str {
        "app.openmkt.marketplace.listing"
    }
    fn def_name() -> &'static str {
        "metadataObj"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_openmkt_marketplace_listing()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

fn lexicon_doc_app_openmkt_marketplace_listing() -> 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.openmkt.marketplace.listing"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("locationObj"),
                LexUserType::Object(LexObject {
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("county"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map.insert(
                            SmolStr::new_static("locality"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map.insert(
                            SmolStr::new_static("state"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map.insert(
                            SmolStr::new_static("zipPrefix"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("title"), SmolStr::new_static("price"),
                                SmolStr::new_static("category"),
                                SmolStr::new_static("location"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("category"),
                                LexObjectProperty::String(LexString {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("condition"),
                                LexObjectProperty::String(LexString {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("description"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(3000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("externalUrl"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Optional external URL for purchasing the item (e.g., Amazon, eBay link)",
                                        ),
                                    ),
                                    max_length: Some(2000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("hideFromFriends"),
                                LexObjectProperty::Boolean(LexBoolean {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("images"),
                                LexObjectProperty::Array(LexArray {
                                    items: LexArrayItem::Blob(LexBlob { ..Default::default() }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("location"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("#locationObj"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("metadata"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("#metadataObj"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("price"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("String representation"),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("title"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(300usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("metadataObj"),
                LexUserType::Object(LexObject {
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("subcategory"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod listing_state {

    pub use crate::builder_types::{Set, Unset, IsSet, IsUnset};
    #[allow(unused)]
    use ::core::marker::PhantomData;
    mod sealed {
        pub trait Sealed {}
    }
    /// State trait tracking which required fields have been set
    pub trait State: sealed::Sealed {
        type Title;
        type Location;
        type Price;
        type Category;
        type CreatedAt;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Title = Unset;
        type Location = Unset;
        type Price = Unset;
        type Category = Unset;
        type CreatedAt = Unset;
    }
    ///State transition - sets the `title` field to Set
    pub struct SetTitle<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetTitle<S> {}
    impl<S: State> State for SetTitle<S> {
        type Title = Set<members::title>;
        type Location = S::Location;
        type Price = S::Price;
        type Category = S::Category;
        type CreatedAt = S::CreatedAt;
    }
    ///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 Title = S::Title;
        type Location = Set<members::location>;
        type Price = S::Price;
        type Category = S::Category;
        type CreatedAt = S::CreatedAt;
    }
    ///State transition - sets the `price` field to Set
    pub struct SetPrice<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetPrice<S> {}
    impl<S: State> State for SetPrice<S> {
        type Title = S::Title;
        type Location = S::Location;
        type Price = Set<members::price>;
        type Category = S::Category;
        type CreatedAt = S::CreatedAt;
    }
    ///State transition - sets the `category` field to Set
    pub struct SetCategory<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetCategory<S> {}
    impl<S: State> State for SetCategory<S> {
        type Title = S::Title;
        type Location = S::Location;
        type Price = S::Price;
        type Category = Set<members::category>;
        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 Title = S::Title;
        type Location = S::Location;
        type Price = S::Price;
        type Category = S::Category;
        type CreatedAt = Set<members::created_at>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `title` field
        pub struct title(());
        ///Marker type for the `location` field
        pub struct location(());
        ///Marker type for the `price` field
        pub struct price(());
        ///Marker type for the `category` field
        pub struct category(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
    }
}

/// Builder for constructing an instance of this type
pub struct ListingBuilder<'a, S: listing_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
        Option<Datetime>,
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
        Option<bool>,
        Option<Vec<BlobRef<'a>>>,
        Option<listing::LocationObj<'a>>,
        Option<listing::MetadataObj<'a>>,
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Listing<'a> {
    /// Create a new builder for this type
    pub fn new() -> ListingBuilder<'a, listing_state::Empty> {
        ListingBuilder::new()
    }
}

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

impl<'a, S> ListingBuilder<'a, S>
where
    S: listing_state::State,
    S::Category: listing_state::IsUnset,
{
    /// Set the `category` field (required)
    pub fn category(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> ListingBuilder<'a, listing_state::SetCategory<S>> {
        self._fields.0 = Option::Some(value.into());
        ListingBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: listing_state::State> ListingBuilder<'a, S> {
    /// Set the `condition` field (optional)
    pub fn condition(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `condition` field to an Option value (optional)
    pub fn maybe_condition(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.1 = value;
        self
    }
}

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

impl<'a, S: listing_state::State> ListingBuilder<'a, S> {
    /// Set the `description` field (optional)
    pub fn description(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `description` field to an Option value (optional)
    pub fn maybe_description(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.3 = value;
        self
    }
}

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

impl<'a, S: listing_state::State> ListingBuilder<'a, S> {
    /// Set the `hideFromFriends` field (optional)
    pub fn hide_from_friends(mut self, value: impl Into<Option<bool>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `hideFromFriends` field to an Option value (optional)
    pub fn maybe_hide_from_friends(mut self, value: Option<bool>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<'a, S: listing_state::State> ListingBuilder<'a, S> {
    /// Set the `images` field (optional)
    pub fn images(mut self, value: impl Into<Option<Vec<BlobRef<'a>>>>) -> Self {
        self._fields.6 = value.into();
        self
    }
    /// Set the `images` field to an Option value (optional)
    pub fn maybe_images(mut self, value: Option<Vec<BlobRef<'a>>>) -> Self {
        self._fields.6 = value;
        self
    }
}

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

impl<'a, S: listing_state::State> ListingBuilder<'a, S> {
    /// Set the `metadata` field (optional)
    pub fn metadata(
        mut self,
        value: impl Into<Option<listing::MetadataObj<'a>>>,
    ) -> Self {
        self._fields.8 = value.into();
        self
    }
    /// Set the `metadata` field to an Option value (optional)
    pub fn maybe_metadata(mut self, value: Option<listing::MetadataObj<'a>>) -> Self {
        self._fields.8 = value;
        self
    }
}

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

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

impl<'a, S> ListingBuilder<'a, S>
where
    S: listing_state::State,
    S::Title: listing_state::IsSet,
    S::Location: listing_state::IsSet,
    S::Price: listing_state::IsSet,
    S::Category: listing_state::IsSet,
    S::CreatedAt: listing_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Listing<'a> {
        Listing {
            category: self._fields.0.unwrap(),
            condition: self._fields.1,
            created_at: self._fields.2.unwrap(),
            description: self._fields.3,
            external_url: self._fields.4,
            hide_from_friends: self._fields.5,
            images: self._fields.6,
            location: self._fields.7.unwrap(),
            metadata: self._fields.8,
            price: self._fields.9.unwrap(),
            title: self._fields.10.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>,
        >,
    ) -> Listing<'a> {
        Listing {
            category: self._fields.0.unwrap(),
            condition: self._fields.1,
            created_at: self._fields.2.unwrap(),
            description: self._fields.3,
            external_url: self._fields.4,
            hide_from_friends: self._fields.5,
            images: self._fields.6,
            location: self._fields.7.unwrap(),
            metadata: self._fields.8,
            price: self._fields.9.unwrap(),
            title: self._fields.10.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}