// @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;

#[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, UriValue};
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_bsky::richtext::facet::Facet;
use crate::community_lexicon::location::hthree::Hthree;
/// A job listing

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Listing<'a> {
    ///URL where applicants can apply for the job.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub apply_link: Option<UriValue<'a>>,
    ///Larger horizontal image to display behind job listing view.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub banner: Option<BlobRef<'a>>,
    ///The description of the job listing.
    #[serde(borrow)]
    pub description: CowStr<'a>,
    ///Annotations of text (mentions, URLs, hashtags, etc).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub facets: Option<Vec<Facet<'a>>>,
    ///Locations that are relevant to the job listing.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub locations: Option<Vec<Hthree<'a>>>,
    ///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.
    #[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>,
}

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())?)
    }
}

/// 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<'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 = "place.atwork.listing";
    type Record = ListingRecord;
}

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

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

/// Builder for constructing an instance of this type
pub struct ListingBuilder<'a, S: listing_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<UriValue<'a>>,
        Option<BlobRef<'a>>,
        Option<CowStr<'a>>,
        Option<Vec<Facet<'a>>>,
        Option<Vec<Hthree<'a>>>,
        Option<Datetime>,
        Option<Datetime>,
        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),
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: listing_state::State> ListingBuilder<'a, S> {
    /// Set the `applyLink` field (optional)
    pub fn apply_link(mut self, value: impl Into<Option<UriValue<'a>>>) -> 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<'a>>) -> Self {
        self._fields.0 = value;
        self
    }
}

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

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

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

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

impl<'a, S> ListingBuilder<'a, S>
where
    S: listing_state::State,
    S::NotBefore: listing_state::IsUnset,
{
    /// Set the `notBefore` field (required)
    pub fn not_before(
        mut self,
        value: impl Into<Datetime>,
    ) -> ListingBuilder<'a, listing_state::SetNotBefore<S>> {
        self._fields.6 = 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.7 = Option::Some(value.into());
        ListingBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> ListingBuilder<'a, S>
where
    S: listing_state::State,
    S::NotAfter: listing_state::IsSet,
    S::NotBefore: listing_state::IsSet,
    S::Title: listing_state::IsSet,
    S::Description: listing_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Listing<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Listing<'a> {
        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()
    }
}