// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: org.hypercerts.claim.rights
//
// 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};
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::org_hypercerts::SmallBlob;
use crate::org_hypercerts::Uri;
/// Describes the rights that a contributor and/or an owner has, such as whether the hypercert can be sold, transferred, and under what conditions.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Rights<'a> {
    ///An attachment to define the rights further, e.g. a legal document.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub attachment: Option<RightsAttachment<'a>>,
    ///Client-declared timestamp when this record was originally created
    pub created_at: Datetime,
    ///Detailed explanation of the rights holders' permissions, restrictions, and conditions
    #[serde(borrow)]
    pub rights_description: CowStr<'a>,
    ///Human-readable name for these rights (e.g. 'All Rights Reserved', 'CC BY-SA 4.0')
    #[serde(borrow)]
    pub rights_name: CowStr<'a>,
    ///Short identifier code for this rights type (e.g. 'ARR', 'CC-BY-SA') to facilitate filtering and search
    #[serde(borrow)]
    pub rights_type: CowStr<'a>,
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type")]
#[serde(bound(deserialize = "'de: 'a"))]
pub enum RightsAttachment<'a> {
    #[serde(rename = "org.hypercerts.defs#uri")]
    Uri(Box<Uri<'a>>),
    #[serde(rename = "org.hypercerts.defs#smallBlob")]
    SmallBlob(Box<SmallBlob<'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 RightsGetRecordOutput<'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: Rights<'a>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct RightsRecord;
impl XrpcResp for RightsRecord {
    const NSID: &'static str = "org.hypercerts.claim.rights";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = RightsGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Rights<'_> {
    const NSID: &'static str = "org.hypercerts.claim.rights";
    type Record = RightsRecord;
}

impl Collection for RightsRecord {
    const NSID: &'static str = "org.hypercerts.claim.rights";
    type Record = RightsRecord;
}

impl<'a> LexiconSchema for Rights<'a> {
    fn nsid() -> &'static str {
        "org.hypercerts.claim.rights"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_org_hypercerts_claim_rights()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.rights_description;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 10000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("rights_description"),
                    max: 10000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.rights_description;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 1000usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("rights_description"),
                        max: 1000usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let value = &self.rights_name;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 100usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("rights_name"),
                    max: 100usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.rights_type;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 10usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("rights_type"),
                    max: 10usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod rights_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 RightsDescription;
        type RightsName;
        type RightsType;
        type CreatedAt;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type RightsDescription = Unset;
        type RightsName = Unset;
        type RightsType = Unset;
        type CreatedAt = Unset;
    }
    ///State transition - sets the `rights_description` field to Set
    pub struct SetRightsDescription<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetRightsDescription<S> {}
    impl<S: State> State for SetRightsDescription<S> {
        type RightsDescription = Set<members::rights_description>;
        type RightsName = S::RightsName;
        type RightsType = S::RightsType;
        type CreatedAt = S::CreatedAt;
    }
    ///State transition - sets the `rights_name` field to Set
    pub struct SetRightsName<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetRightsName<S> {}
    impl<S: State> State for SetRightsName<S> {
        type RightsDescription = S::RightsDescription;
        type RightsName = Set<members::rights_name>;
        type RightsType = S::RightsType;
        type CreatedAt = S::CreatedAt;
    }
    ///State transition - sets the `rights_type` field to Set
    pub struct SetRightsType<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetRightsType<S> {}
    impl<S: State> State for SetRightsType<S> {
        type RightsDescription = S::RightsDescription;
        type RightsName = S::RightsName;
        type RightsType = Set<members::rights_type>;
        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 RightsDescription = S::RightsDescription;
        type RightsName = S::RightsName;
        type RightsType = S::RightsType;
        type CreatedAt = Set<members::created_at>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `rights_description` field
        pub struct rights_description(());
        ///Marker type for the `rights_name` field
        pub struct rights_name(());
        ///Marker type for the `rights_type` field
        pub struct rights_type(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
    }
}

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

impl<'a> Rights<'a> {
    /// Create a new builder for this type
    pub fn new() -> RightsBuilder<'a, rights_state::Empty> {
        RightsBuilder::new()
    }
}

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

impl<'a, S: rights_state::State> RightsBuilder<'a, S> {
    /// Set the `attachment` field (optional)
    pub fn attachment(mut self, value: impl Into<Option<RightsAttachment<'a>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `attachment` field to an Option value (optional)
    pub fn maybe_attachment(mut self, value: Option<RightsAttachment<'a>>) -> Self {
        self._fields.0 = value;
        self
    }
}

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

impl<'a, S> RightsBuilder<'a, S>
where
    S: rights_state::State,
    S::RightsDescription: rights_state::IsUnset,
{
    /// Set the `rightsDescription` field (required)
    pub fn rights_description(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> RightsBuilder<'a, rights_state::SetRightsDescription<S>> {
        self._fields.2 = Option::Some(value.into());
        RightsBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> RightsBuilder<'a, S>
where
    S: rights_state::State,
    S::RightsName: rights_state::IsUnset,
{
    /// Set the `rightsName` field (required)
    pub fn rights_name(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> RightsBuilder<'a, rights_state::SetRightsName<S>> {
        self._fields.3 = Option::Some(value.into());
        RightsBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> RightsBuilder<'a, S>
where
    S: rights_state::State,
    S::RightsType: rights_state::IsUnset,
{
    /// Set the `rightsType` field (required)
    pub fn rights_type(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> RightsBuilder<'a, rights_state::SetRightsType<S>> {
        self._fields.4 = Option::Some(value.into());
        RightsBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> RightsBuilder<'a, S>
where
    S: rights_state::State,
    S::RightsDescription: rights_state::IsSet,
    S::RightsName: rights_state::IsSet,
    S::RightsType: rights_state::IsSet,
    S::CreatedAt: rights_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Rights<'a> {
        Rights {
            attachment: self._fields.0,
            created_at: self._fields.1.unwrap(),
            rights_description: self._fields.2.unwrap(),
            rights_name: self._fields.3.unwrap(),
            rights_type: self._fields.4.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>,
        >,
    ) -> Rights<'a> {
        Rights {
            attachment: self._fields.0,
            created_at: self._fields.1.unwrap(),
            rights_description: self._fields.2.unwrap(),
            rights_name: self._fields.3.unwrap(),
            rights_type: self._fields.4.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_org_hypercerts_claim_rights() -> 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("org.hypercerts.claim.rights"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "Describes the rights that a contributor and/or an owner has, such as whether the hypercert can be sold, transferred, and under what conditions.",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("rightsName"),
                                SmolStr::new_static("rightsType"),
                                SmolStr::new_static("rightsDescription"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("attachment"),
                                LexObjectProperty::Union(LexRefUnion {
                                    description: Some(
                                        CowStr::new_static(
                                            "An attachment to define the rights further, e.g. a legal document.",
                                        ),
                                    ),
                                    refs: vec![
                                        CowStr::new_static("org.hypercerts.defs#uri"),
                                        CowStr::new_static("org.hypercerts.defs#smallBlob")
                                    ],
                                    ..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("rightsDescription"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Detailed explanation of the rights holders' permissions, restrictions, and conditions",
                                        ),
                                    ),
                                    max_length: Some(10000usize),
                                    max_graphemes: Some(1000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("rightsName"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Human-readable name for these rights (e.g. 'All Rights Reserved', 'CC BY-SA 4.0')",
                                        ),
                                    ),
                                    max_length: Some(100usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("rightsType"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Short identifier code for this rights type (e.g. 'ARR', 'CC-BY-SA') to facilitate filtering and search",
                                        ),
                                    ),
                                    max_length: Some(10usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}