// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: app.certified.badge.award
//
// This file was automatically generated from Lexicon schemas.
// Any manual changes will be overwritten on the next regeneration.

#[allow(unused_imports)]
use alloc::collections::BTreeMap;

#[allow(unused_imports)]
use core::marker::PhantomData;
use jacquard_common::CowStr;

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
use jacquard_common::types::collection::{Collection, RecordError};
use jacquard_common::types::string::{AtUri, Cid, Datetime, UriValue};
use jacquard_common::types::uri::{RecordUri, UriError};
use jacquard_common::xrpc::XrpcResp;
use jacquard_derive::{IntoStatic, lexicon, open_union};
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_certified::Did;
use crate::app_certified::badge::definition::Definition;
use crate::com_atproto::repo::strong_ref::StrongRef;
/// Records a badge award to a user, project, or activity claim.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Award<'a> {
    ///Reference to the badge definition for this award.
    #[serde(borrow)]
    pub badge: Definition<'a>,
    ///Client-declared timestamp when this record was originally created
    pub created_at: Datetime,
    ///Optional statement explaining the reason for this badge award.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub note: Option<CowStr<'a>>,
    ///Entity the badge award is for (either an account DID or any specific AT Protocol record), e.g. a user, a project, or a specific activity claim.
    #[serde(borrow)]
    pub subject: AwardSubject<'a>,
    ///Optional URL the badge award links to.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub url: Option<UriValue<'a>>,
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type")]
#[serde(bound(deserialize = "'de: 'a"))]
pub enum AwardSubject<'a> {
    #[serde(rename = "app.certified.defs#did")]
    Did(Box<Did<'a>>),
    #[serde(rename = "com.atproto.repo.strongRef")]
    StrongRef(Box<StrongRef<'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 AwardGetRecordOutput<'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: Award<'a>,
}

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

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

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

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

impl Collection for Award<'_> {
    const NSID: &'static str = "app.certified.badge.award";
    type Record = AwardRecord;
}

impl Collection for AwardRecord {
    const NSID: &'static str = "app.certified.badge.award";
    type Record = AwardRecord;
}

impl<'a> LexiconSchema for Award<'a> {
    fn nsid() -> &'static str {
        "app.certified.badge.award"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_certified_badge_award()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.note {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 500usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("note"),
                    max: 500usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.url {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 2048usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("url"),
                    max: 2048usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod award_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 Subject;
        type Badge;
        type CreatedAt;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Subject = Unset;
        type Badge = Unset;
        type CreatedAt = Unset;
    }
    ///State transition - sets the `subject` field to Set
    pub struct SetSubject<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetSubject<S> {}
    impl<S: State> State for SetSubject<S> {
        type Subject = Set<members::subject>;
        type Badge = S::Badge;
        type CreatedAt = S::CreatedAt;
    }
    ///State transition - sets the `badge` field to Set
    pub struct SetBadge<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetBadge<S> {}
    impl<S: State> State for SetBadge<S> {
        type Subject = S::Subject;
        type Badge = Set<members::badge>;
        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 Subject = S::Subject;
        type Badge = S::Badge;
        type CreatedAt = Set<members::created_at>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `subject` field
        pub struct subject(());
        ///Marker type for the `badge` field
        pub struct badge(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
    }
}

/// Builder for constructing an instance of this type
pub struct AwardBuilder<'a, S: award_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Definition<'a>>,
        Option<Datetime>,
        Option<CowStr<'a>>,
        Option<AwardSubject<'a>>,
        Option<UriValue<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Award<'a> {
    /// Create a new builder for this type
    pub fn new() -> AwardBuilder<'a, award_state::Empty> {
        AwardBuilder::new()
    }
}

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

impl<'a, S> AwardBuilder<'a, S>
where
    S: award_state::State,
    S::Badge: award_state::IsUnset,
{
    /// Set the `badge` field (required)
    pub fn badge(
        mut self,
        value: impl Into<Definition<'a>>,
    ) -> AwardBuilder<'a, award_state::SetBadge<S>> {
        self._fields.0 = Option::Some(value.into());
        AwardBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

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

impl<'a, S: award_state::State> AwardBuilder<'a, S> {
    /// Set the `note` field (optional)
    pub fn note(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `note` field to an Option value (optional)
    pub fn maybe_note(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<'a, S> AwardBuilder<'a, S>
where
    S: award_state::State,
    S::Subject: award_state::IsUnset,
{
    /// Set the `subject` field (required)
    pub fn subject(
        mut self,
        value: impl Into<AwardSubject<'a>>,
    ) -> AwardBuilder<'a, award_state::SetSubject<S>> {
        self._fields.3 = Option::Some(value.into());
        AwardBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: award_state::State> AwardBuilder<'a, S> {
    /// Set the `url` field (optional)
    pub fn url(mut self, value: impl Into<Option<UriValue<'a>>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `url` field to an Option value (optional)
    pub fn maybe_url(mut self, value: Option<UriValue<'a>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<'a, S> AwardBuilder<'a, S>
where
    S: award_state::State,
    S::Subject: award_state::IsSet,
    S::Badge: award_state::IsSet,
    S::CreatedAt: award_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Award<'a> {
        Award {
            badge: self._fields.0.unwrap(),
            created_at: self._fields.1.unwrap(),
            note: self._fields.2,
            subject: self._fields.3.unwrap(),
            url: self._fields.4,
            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>,
        >,
    ) -> Award<'a> {
        Award {
            badge: self._fields.0.unwrap(),
            created_at: self._fields.1.unwrap(),
            note: self._fields.2,
            subject: self._fields.3.unwrap(),
            url: self._fields.4,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_app_certified_badge_award() -> 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.certified.badge.award"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "Records a badge award to a user, project, or activity claim.",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("badge"),
                                SmolStr::new_static("subject"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("badge"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("app.certified.badge.definition"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Client-declared timestamp when this record was originally created",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("note"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Optional statement explaining the reason for this badge award.",
                                        ),
                                    ),
                                    max_length: Some(500usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("subject"),
                                LexObjectProperty::Union(LexRefUnion {
                                    description: Some(
                                        CowStr::new_static(
                                            "Entity the badge award is for (either an account DID or any specific AT Protocol record), e.g. a user, a project, or a specific activity claim.",
                                        ),
                                    ),
                                    refs: vec![
                                        CowStr::new_static("app.certified.defs#did"),
                                        CowStr::new_static("com.atproto.repo.strongRef")
                                    ],
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("url"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Optional URL the badge award links to."),
                                    ),
                                    format: Some(LexStringFormat::Uri),
                                    max_length: Some(2048usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}