// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: org.hypercerts.funding.receipt
//
// 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};
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;
/// Records a funding receipt for a payment from one user to another user. It may be recorded by the recipient, by the sender, or by a third party. The sender may remain anonymous.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Receipt<'a> {
    ///Amount of funding received as a numeric string (e.g. '1000.50').
    #[serde(borrow)]
    pub amount: CowStr<'a>,
    ///Client-declared timestamp when this receipt record was created.
    pub created_at: Datetime,
    ///Currency of the payment (e.g. EUR, USD, ETH).
    #[serde(borrow)]
    pub currency: CowStr<'a>,
    ///Optional reference to the activity, project, or organization this funding relates to.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub r#for: Option<AtUri<'a>>,
    ///DID of the sender who transferred the funds. Leave empty if sender wants to stay anonymous.
    #[serde(borrow)]
    pub from: Did<'a>,
    ///Optional notes or additional context for this funding receipt.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub notes: Option<CowStr<'a>>,
    ///Timestamp when the payment occurred.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub occurred_at: Option<Datetime>,
    ///Optional network within the payment rail (e.g. arbitrum, ethereum, sepa, visa, paypal).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub payment_network: Option<CowStr<'a>>,
    ///How the funds were transferred (e.g. bank_transfer, credit_card, onchain, cash, check, payment_processor).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub payment_rail: Option<CowStr<'a>>,
    ///The recipient of the funds. Can be identified by DID or a clear-text name.
    #[serde(borrow)]
    pub to: CowStr<'a>,
    ///Identifier of the underlying payment transaction (e.g. bank reference, onchain transaction hash, or processor-specific ID). Use paymentNetwork to specify the network where applicable.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub transaction_id: Option<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 ReceiptGetRecordOutput<'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: Receipt<'a>,
}

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

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

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

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

impl Collection for Receipt<'_> {
    const NSID: &'static str = "org.hypercerts.funding.receipt";
    type Record = ReceiptRecord;
}

impl Collection for ReceiptRecord {
    const NSID: &'static str = "org.hypercerts.funding.receipt";
    type Record = ReceiptRecord;
}

impl<'a> LexiconSchema for Receipt<'a> {
    fn nsid() -> &'static str {
        "org.hypercerts.funding.receipt"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_org_hypercerts_funding_receipt()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.amount;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 50usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("amount"),
                    max: 50usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.currency;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 10usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("currency"),
                    max: 10usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.notes {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 500usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("notes"),
                    max: 500usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.payment_network {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 50usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("payment_network"),
                    max: 50usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.payment_rail {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 50usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("payment_rail"),
                    max: 50usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.to;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 2048usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("to"),
                    max: 2048usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.transaction_id {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 256usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("transaction_id"),
                    max: 256usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod receipt_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 From;
        type Amount;
        type Currency;
        type To;
        type CreatedAt;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type From = Unset;
        type Amount = Unset;
        type Currency = Unset;
        type To = Unset;
        type CreatedAt = Unset;
    }
    ///State transition - sets the `from` field to Set
    pub struct SetFrom<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetFrom<S> {}
    impl<S: State> State for SetFrom<S> {
        type From = Set<members::from>;
        type Amount = S::Amount;
        type Currency = S::Currency;
        type To = S::To;
        type CreatedAt = S::CreatedAt;
    }
    ///State transition - sets the `amount` field to Set
    pub struct SetAmount<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetAmount<S> {}
    impl<S: State> State for SetAmount<S> {
        type From = S::From;
        type Amount = Set<members::amount>;
        type Currency = S::Currency;
        type To = S::To;
        type CreatedAt = S::CreatedAt;
    }
    ///State transition - sets the `currency` field to Set
    pub struct SetCurrency<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetCurrency<S> {}
    impl<S: State> State for SetCurrency<S> {
        type From = S::From;
        type Amount = S::Amount;
        type Currency = Set<members::currency>;
        type To = S::To;
        type CreatedAt = S::CreatedAt;
    }
    ///State transition - sets the `to` field to Set
    pub struct SetTo<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetTo<S> {}
    impl<S: State> State for SetTo<S> {
        type From = S::From;
        type Amount = S::Amount;
        type Currency = S::Currency;
        type To = Set<members::to>;
        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 From = S::From;
        type Amount = S::Amount;
        type Currency = S::Currency;
        type To = S::To;
        type CreatedAt = Set<members::created_at>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `from` field
        pub struct from(());
        ///Marker type for the `amount` field
        pub struct amount(());
        ///Marker type for the `currency` field
        pub struct currency(());
        ///Marker type for the `to` field
        pub struct to(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
    }
}

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

impl<'a> Receipt<'a> {
    /// Create a new builder for this type
    pub fn new() -> ReceiptBuilder<'a, receipt_state::Empty> {
        ReceiptBuilder::new()
    }
}

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

impl<'a, S> ReceiptBuilder<'a, S>
where
    S: receipt_state::State,
    S::Amount: receipt_state::IsUnset,
{
    /// Set the `amount` field (required)
    pub fn amount(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> ReceiptBuilder<'a, receipt_state::SetAmount<S>> {
        self._fields.0 = Option::Some(value.into());
        ReceiptBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

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

impl<'a, S> ReceiptBuilder<'a, S>
where
    S: receipt_state::State,
    S::Currency: receipt_state::IsUnset,
{
    /// Set the `currency` field (required)
    pub fn currency(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> ReceiptBuilder<'a, receipt_state::SetCurrency<S>> {
        self._fields.2 = Option::Some(value.into());
        ReceiptBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: receipt_state::State> ReceiptBuilder<'a, S> {
    /// Set the `for` field (optional)
    pub fn r#for(mut self, value: impl Into<Option<AtUri<'a>>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `for` field to an Option value (optional)
    pub fn maybe_for(mut self, value: Option<AtUri<'a>>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<'a, S> ReceiptBuilder<'a, S>
where
    S: receipt_state::State,
    S::From: receipt_state::IsUnset,
{
    /// Set the `from` field (required)
    pub fn from(
        mut self,
        value: impl Into<Did<'a>>,
    ) -> ReceiptBuilder<'a, receipt_state::SetFrom<S>> {
        self._fields.4 = Option::Some(value.into());
        ReceiptBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: receipt_state::State> ReceiptBuilder<'a, S> {
    /// Set the `notes` field (optional)
    pub fn notes(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `notes` field to an Option value (optional)
    pub fn maybe_notes(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<'a, S: receipt_state::State> ReceiptBuilder<'a, S> {
    /// Set the `occurredAt` field (optional)
    pub fn occurred_at(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.6 = value.into();
        self
    }
    /// Set the `occurredAt` field to an Option value (optional)
    pub fn maybe_occurred_at(mut self, value: Option<Datetime>) -> Self {
        self._fields.6 = value;
        self
    }
}

impl<'a, S: receipt_state::State> ReceiptBuilder<'a, S> {
    /// Set the `paymentNetwork` field (optional)
    pub fn payment_network(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `paymentNetwork` field to an Option value (optional)
    pub fn maybe_payment_network(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<'a, S: receipt_state::State> ReceiptBuilder<'a, S> {
    /// Set the `paymentRail` field (optional)
    pub fn payment_rail(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.8 = value.into();
        self
    }
    /// Set the `paymentRail` field to an Option value (optional)
    pub fn maybe_payment_rail(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.8 = value;
        self
    }
}

impl<'a, S> ReceiptBuilder<'a, S>
where
    S: receipt_state::State,
    S::To: receipt_state::IsUnset,
{
    /// Set the `to` field (required)
    pub fn to(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> ReceiptBuilder<'a, receipt_state::SetTo<S>> {
        self._fields.9 = Option::Some(value.into());
        ReceiptBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: receipt_state::State> ReceiptBuilder<'a, S> {
    /// Set the `transactionId` field (optional)
    pub fn transaction_id(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.10 = value.into();
        self
    }
    /// Set the `transactionId` field to an Option value (optional)
    pub fn maybe_transaction_id(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.10 = value;
        self
    }
}

impl<'a, S> ReceiptBuilder<'a, S>
where
    S: receipt_state::State,
    S::From: receipt_state::IsSet,
    S::Amount: receipt_state::IsSet,
    S::Currency: receipt_state::IsSet,
    S::To: receipt_state::IsSet,
    S::CreatedAt: receipt_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Receipt<'a> {
        Receipt {
            amount: self._fields.0.unwrap(),
            created_at: self._fields.1.unwrap(),
            currency: self._fields.2.unwrap(),
            r#for: self._fields.3,
            from: self._fields.4.unwrap(),
            notes: self._fields.5,
            occurred_at: self._fields.6,
            payment_network: self._fields.7,
            payment_rail: self._fields.8,
            to: self._fields.9.unwrap(),
            transaction_id: self._fields.10,
            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>,
        >,
    ) -> Receipt<'a> {
        Receipt {
            amount: self._fields.0.unwrap(),
            created_at: self._fields.1.unwrap(),
            currency: self._fields.2.unwrap(),
            r#for: self._fields.3,
            from: self._fields.4.unwrap(),
            notes: self._fields.5,
            occurred_at: self._fields.6,
            payment_network: self._fields.7,
            payment_rail: self._fields.8,
            to: self._fields.9.unwrap(),
            transaction_id: self._fields.10,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_org_hypercerts_funding_receipt() -> 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.funding.receipt"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "Records a funding receipt for a payment from one user to another user. It may be recorded by the recipient, by the sender, or by a third party. The sender may remain anonymous.",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("from"), SmolStr::new_static("to"),
                                SmolStr::new_static("amount"),
                                SmolStr::new_static("currency"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("amount"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Amount of funding received as a numeric string (e.g. '1000.50').",
                                        ),
                                    ),
                                    max_length: Some(50usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Client-declared timestamp when this receipt record was created.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("currency"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Currency of the payment (e.g. EUR, USD, ETH).",
                                        ),
                                    ),
                                    max_length: Some(10usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("for"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Optional reference to the activity, project, or organization this funding relates to.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::AtUri),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("from"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("app.certified.defs#did"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("notes"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Optional notes or additional context for this funding receipt.",
                                        ),
                                    ),
                                    max_length: Some(500usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("occurredAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Timestamp when the payment occurred."),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("paymentNetwork"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Optional network within the payment rail (e.g. arbitrum, ethereum, sepa, visa, paypal).",
                                        ),
                                    ),
                                    max_length: Some(50usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("paymentRail"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "How the funds were transferred (e.g. bank_transfer, credit_card, onchain, cash, check, payment_processor).",
                                        ),
                                    ),
                                    max_length: Some(50usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("to"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The recipient of the funds. Can be identified by DID or a clear-text name.",
                                        ),
                                    ),
                                    max_length: Some(2048usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("transactionId"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Identifier of the underlying payment transaction (e.g. bank reference, onchain transaction hash, or processor-specific ID). Use paymentNetwork to specify the network where applicable.",
                                        ),
                                    ),
                                    max_length: Some(256usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}