// @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, BosStr, DefaultStr, FromStaticStr};

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
use jacquard_common::deps::smol_str::SmolStr;
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::types::value::Data;
use jacquard_common::xrpc::XrpcResp;
use jacquard_derive::{IntoStatic, lexicon};
use jacquard_lexicon::lexicon::LexiconDoc;
use jacquard_lexicon::schema::LexiconSchema;

#[allow(unused_imports)]
use jacquard_lexicon::validation::{ConstraintError, ValidationPath};
use serde::{Serialize, Deserialize};
use crate::app_openmkt::marketplace::listing;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct LocationObj<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub county: Option<S>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub locality: Option<S>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<S>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub zip_prefix: Option<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "app.openmkt.marketplace.listing",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Listing<S: BosStr = DefaultStr> {
    pub category: S,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub condition: Option<S>,
    pub created_at: Datetime,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<S>,
    ///Optional external URL for purchasing the item (e.g., Amazon, eBay link)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub external_url: Option<S>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hide_from_friends: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub images: Option<Vec<BlobRef<S>>>,
    pub location: listing::LocationObj<S>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<listing::MetadataObj<S>>,
    ///String representation
    pub price: S,
    pub title: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// 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<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Listing<S>,
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct MetadataObj<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subcategory: Option<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

impl<S: BosStr> Listing<S> {
    pub fn uri(uri: S) -> Result<RecordUri<S, ListingRecord>, UriError> {
        RecordUri::try_from_uri(AtUri::new(uri)?)
    }
}

impl<S: BosStr> LexiconSchema for LocationObj<S> {
    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<S: BosStr> = ListingGetRecordOutput<S>;
    type Err = RecordError;
}

impl<S: BosStr> From<ListingGetRecordOutput<S>> for Listing<S> {
    fn from(output: ListingGetRecordOutput<S>) -> Self {
        output.value
    }
}

impl<S: BosStr> Collection for Listing<S> {
    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<S: BosStr> LexiconSchema for Listing<S> {
    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<S: BosStr> LexiconSchema for MetadataObj<S> {
    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 Category;
        type CreatedAt;
        type Location;
        type Price;
        type Title;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Category = Unset;
        type CreatedAt = Unset;
        type Location = Unset;
        type Price = Unset;
        type Title = Unset;
    }
    ///State transition - sets the `category` field to Set
    pub struct SetCategory<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetCategory<St> {}
    impl<St: State> State for SetCategory<St> {
        type Category = Set<members::category>;
        type CreatedAt = St::CreatedAt;
        type Location = St::Location;
        type Price = St::Price;
        type Title = St::Title;
    }
    ///State transition - sets the `created_at` field to Set
    pub struct SetCreatedAt<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetCreatedAt<St> {}
    impl<St: State> State for SetCreatedAt<St> {
        type Category = St::Category;
        type CreatedAt = Set<members::created_at>;
        type Location = St::Location;
        type Price = St::Price;
        type Title = St::Title;
    }
    ///State transition - sets the `location` field to Set
    pub struct SetLocation<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetLocation<St> {}
    impl<St: State> State for SetLocation<St> {
        type Category = St::Category;
        type CreatedAt = St::CreatedAt;
        type Location = Set<members::location>;
        type Price = St::Price;
        type Title = St::Title;
    }
    ///State transition - sets the `price` field to Set
    pub struct SetPrice<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetPrice<St> {}
    impl<St: State> State for SetPrice<St> {
        type Category = St::Category;
        type CreatedAt = St::CreatedAt;
        type Location = St::Location;
        type Price = Set<members::price>;
        type Title = St::Title;
    }
    ///State transition - sets the `title` field to Set
    pub struct SetTitle<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetTitle<St> {}
    impl<St: State> State for SetTitle<St> {
        type Category = St::Category;
        type CreatedAt = St::CreatedAt;
        type Location = St::Location;
        type Price = St::Price;
        type Title = Set<members::title>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `category` field
        pub struct category(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `location` field
        pub struct location(());
        ///Marker type for the `price` field
        pub struct price(());
        ///Marker type for the `title` field
        pub struct title(());
    }
}

/// Builder for constructing an instance of this type.
pub struct ListingBuilder<St: listing_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<S>,
        Option<S>,
        Option<Datetime>,
        Option<S>,
        Option<S>,
        Option<bool>,
        Option<Vec<BlobRef<S>>>,
        Option<listing::LocationObj<S>>,
        Option<listing::MetadataObj<S>>,
        Option<S>,
        Option<S>,
    ),
    _type: PhantomData<fn() -> S>,
}

impl Listing<DefaultStr> {
    /// Create a new builder for this type, using the default string type (DefaultStr = SmolStr) if needed
    pub fn new() -> ListingBuilder<listing_state::Empty, DefaultStr> {
        ListingBuilder::new()
    }
}

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

impl ListingBuilder<listing_state::Empty, DefaultStr> {
    /// Create a new builder with all fields unset, using the default string type, if needed
    pub fn new() -> Self {
        ListingBuilder {
            _state: PhantomData,
            _fields: (None, None, None, None, None, None, None, None, None, None, None),
            _type: PhantomData,
        }
    }
}

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

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

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

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

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

impl<St: listing_state::State, S: BosStr> ListingBuilder<St, S> {
    /// Set the `externalUrl` field (optional)
    pub fn external_url(mut self, value: impl Into<Option<S>>) -> 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<S>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St: listing_state::State, S: BosStr> ListingBuilder<St, 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<St: listing_state::State, S: BosStr> ListingBuilder<St, S> {
    /// Set the `images` field (optional)
    pub fn images(mut self, value: impl Into<Option<Vec<BlobRef<S>>>>) -> 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<S>>>) -> Self {
        self._fields.6 = value;
        self
    }
}

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

impl<St: listing_state::State, S: BosStr> ListingBuilder<St, S> {
    /// Set the `metadata` field (optional)
    pub fn metadata(
        mut self,
        value: impl Into<Option<listing::MetadataObj<S>>>,
    ) -> 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<S>>) -> Self {
        self._fields.8 = value;
        self
    }
}

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

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

impl<St, S: BosStr> ListingBuilder<St, S>
where
    St: listing_state::State,
    St::Category: listing_state::IsSet,
    St::CreatedAt: listing_state::IsSet,
    St::Location: listing_state::IsSet,
    St::Price: listing_state::IsSet,
    St::Title: listing_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Listing<S> {
        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<SmolStr, Data<S>>) -> Listing<S> {
        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),
        }
    }
}