// @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, 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::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, 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.

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


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

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

/// 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<S: BosStr> = RightsGetRecordOutput<S>;
    type Err = RecordError;
}

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

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

/// Builder for constructing an instance of this type.
pub struct RightsBuilder<St: rights_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<RightsAttachment<S>>,
        Option<Datetime>,
        Option<S>,
        Option<S>,
        Option<S>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

impl<St: rights_state::State, S: BosStr> RightsBuilder<St, S> {
    /// Set the `attachment` field (optional)
    pub fn attachment(mut self, value: impl Into<Option<RightsAttachment<S>>>) -> 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<S>>) -> Self {
        self._fields.0 = value;
        self
    }
}

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

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

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

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

impl<St, S: BosStr> RightsBuilder<St, S>
where
    St: rights_state::State,
    St::CreatedAt: rights_state::IsSet,
    St::RightsDescription: rights_state::IsSet,
    St::RightsName: rights_state::IsSet,
    St::RightsType: rights_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Rights<S> {
        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<SmolStr, Data<S>>) -> Rights<S> {
        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()
    }
}