// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: place.atwork.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, UriValue};
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_bsky::richtext::facet::Facet;
use crate::community_lexicon::location::hthree::Hthree;
/// A job listing

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "place.atwork.listing",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Listing<S: BosStr = DefaultStr> {
    ///URL where applicants can apply for the job.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub apply_link: Option<UriValue<S>>,
    ///Larger horizontal image to display behind job listing view.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub banner: Option<BlobRef<S>>,
    ///The description of the job listing.
    pub description: S,
    ///Annotations of text (mentions, URLs, hashtags, etc).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub facets: Option<Vec<Facet<S>>>,
    ///Locations that are relevant to the job listing.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub locations: Option<Vec<Hthree<S>>>,
    ///Client-declared timestamp when the job listing expires.
    pub not_after: Datetime,
    ///Client-declared timestamp when the job listing becomes visible.
    pub not_before: Datetime,
    ///The title of the job listing.
    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>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct ListingRecord;
impl XrpcResp for ListingRecord {
    const NSID: &'static str = "place.atwork.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 = "place.atwork.listing";
    type Record = ListingRecord;
}

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

impl<S: BosStr> LexiconSchema for Listing<S> {
    fn nsid() -> &'static str {
        "place.atwork.listing"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_place_atwork_listing()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.banner {
            {
                let size = value.blob().size;
                if size > 1000000usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("banner"),
                        max: 1000000usize,
                        actual: size,
                    });
                }
            }
        }
        if let Some(ref value) = self.banner {
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &["image/png", "image/jpeg"];
                let matched = accepted
                    .iter()
                    .any(|pattern| {
                        if *pattern == "*/*" {
                            true
                        } else if pattern.ends_with("/*") {
                            let prefix = &pattern[..pattern.len() - 2];
                            mime.starts_with(prefix)
                                && mime.as_bytes().get(prefix.len()) == Some(&b'/')
                        } else {
                            mime == *pattern
                        }
                    });
                if !matched {
                    return Err(ConstraintError::BlobMimeTypeNotAccepted {
                        path: ValidationPath::from_field("banner"),
                        accepted: vec![
                            "image/png".to_string(), "image/jpeg".to_string()
                        ],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        {
            let value = &self.description;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 10000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("description"),
                    max: 10000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.description;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 10000usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("description"),
                        max: 10000usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let value = &self.title;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 200usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("title"),
                    max: 200usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

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 Description;
        type NotAfter;
        type NotBefore;
        type Title;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Description = Unset;
        type NotAfter = Unset;
        type NotBefore = Unset;
        type Title = Unset;
    }
    ///State transition - sets the `description` field to Set
    pub struct SetDescription<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetDescription<St> {}
    impl<St: State> State for SetDescription<St> {
        type Description = Set<members::description>;
        type NotAfter = St::NotAfter;
        type NotBefore = St::NotBefore;
        type Title = St::Title;
    }
    ///State transition - sets the `not_after` field to Set
    pub struct SetNotAfter<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetNotAfter<St> {}
    impl<St: State> State for SetNotAfter<St> {
        type Description = St::Description;
        type NotAfter = Set<members::not_after>;
        type NotBefore = St::NotBefore;
        type Title = St::Title;
    }
    ///State transition - sets the `not_before` field to Set
    pub struct SetNotBefore<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetNotBefore<St> {}
    impl<St: State> State for SetNotBefore<St> {
        type Description = St::Description;
        type NotAfter = St::NotAfter;
        type NotBefore = Set<members::not_before>;
        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 Description = St::Description;
        type NotAfter = St::NotAfter;
        type NotBefore = St::NotBefore;
        type Title = Set<members::title>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `description` field
        pub struct description(());
        ///Marker type for the `not_after` field
        pub struct not_after(());
        ///Marker type for the `not_before` field
        pub struct not_before(());
        ///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<UriValue<S>>,
        Option<BlobRef<S>>,
        Option<S>,
        Option<Vec<Facet<S>>>,
        Option<Vec<Hthree<S>>>,
        Option<Datetime>,
        Option<Datetime>,
        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),
            _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),
            _type: PhantomData,
        }
    }
}

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

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

impl<St, S: BosStr> ListingBuilder<St, S>
where
    St: listing_state::State,
    St::Description: listing_state::IsUnset,
{
    /// Set the `description` field (required)
    pub fn description(
        mut self,
        value: impl Into<S>,
    ) -> ListingBuilder<listing_state::SetDescription<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 `facets` field (optional)
    pub fn facets(mut self, value: impl Into<Option<Vec<Facet<S>>>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `facets` field to an Option value (optional)
    pub fn maybe_facets(mut self, value: Option<Vec<Facet<S>>>) -> Self {
        self._fields.3 = value;
        self
    }
}

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

impl<St, S: BosStr> ListingBuilder<St, S>
where
    St: listing_state::State,
    St::NotAfter: listing_state::IsUnset,
{
    /// Set the `notAfter` field (required)
    pub fn not_after(
        mut self,
        value: impl Into<Datetime>,
    ) -> ListingBuilder<listing_state::SetNotAfter<St>, S> {
        self._fields.5 = 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::NotBefore: listing_state::IsUnset,
{
    /// Set the `notBefore` field (required)
    pub fn not_before(
        mut self,
        value: impl Into<Datetime>,
    ) -> ListingBuilder<listing_state::SetNotBefore<St>, S> {
        self._fields.6 = 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.7 = 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::Description: listing_state::IsSet,
    St::NotAfter: listing_state::IsSet,
    St::NotBefore: listing_state::IsSet,
    St::Title: listing_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Listing<S> {
        Listing {
            apply_link: self._fields.0,
            banner: self._fields.1,
            description: self._fields.2.unwrap(),
            facets: self._fields.3,
            locations: self._fields.4,
            not_after: self._fields.5.unwrap(),
            not_before: self._fields.6.unwrap(),
            title: self._fields.7.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 {
            apply_link: self._fields.0,
            banner: self._fields.1,
            description: self._fields.2.unwrap(),
            facets: self._fields.3,
            locations: self._fields.4,
            not_after: self._fields.5.unwrap(),
            not_before: self._fields.6.unwrap(),
            title: self._fields.7.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_place_atwork_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("place.atwork.listing"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(CowStr::new_static("A job listing")),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("title"),
                                SmolStr::new_static("notBefore"),
                                SmolStr::new_static("notAfter"),
                                SmolStr::new_static("description")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("applyLink"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "URL where applicants can apply for the job.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Uri),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("banner"),
                                LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                            );
                            map.insert(
                                SmolStr::new_static("description"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("The description of the job listing."),
                                    ),
                                    max_length: Some(10000usize),
                                    max_graphemes: Some(10000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("facets"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Annotations of text (mentions, URLs, hashtags, etc).",
                                        ),
                                    ),
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("app.bsky.richtext.facet"),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("locations"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Locations that are relevant to the job listing.",
                                        ),
                                    ),
                                    items: LexArrayItem::Union(LexRefUnion {
                                        refs: vec![
                                            CowStr::new_static("community.lexicon.location.hthree")
                                        ],
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("notAfter"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Client-declared timestamp when the job listing expires.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("notBefore"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Client-declared timestamp when the job listing becomes visible.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("title"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("The title of the job listing."),
                                    ),
                                    max_length: Some(200usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}