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

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "org.hypercerts.funding.receipt",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Receipt<S: BosStr = DefaultStr> {
    ///Amount of funding received as a numeric string (e.g. '1000.50').
    pub amount: S,
    ///Client-declared timestamp when this receipt record was created.
    pub created_at: Datetime,
    ///Currency of the payment (e.g. EUR, USD, ETH).
    pub currency: S,
    ///Optional reference to the activity, project, or organization this funding relates to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub r#for: Option<AtUri<S>>,
    ///DID of the sender who transferred the funds. Leave empty if sender wants to stay anonymous.
    pub from: Did<S>,
    ///Optional notes or additional context for this funding receipt.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notes: Option<S>,
    ///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")]
    pub payment_network: Option<S>,
    ///How the funds were transferred (e.g. bank_transfer, credit_card, onchain, cash, check, payment_processor).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_rail: Option<S>,
    ///The recipient of the funds. Can be identified by DID or a clear-text name.
    pub to: S,
    ///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")]
    pub transaction_id: Option<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<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 ReceiptGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Receipt<S>,
}

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

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

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

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

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

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

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

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

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

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

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

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

impl<St: receipt_state::State, S: BosStr> ReceiptBuilder<St, S> {
    /// Set the `for` field (optional)
    pub fn r#for(mut self, value: impl Into<Option<AtUri<S>>>) -> 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<S>>) -> Self {
        self._fields.3 = value;
        self
    }
}

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

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

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

impl<St: receipt_state::State, S: BosStr> ReceiptBuilder<St, S> {
    /// Set the `paymentRail` field (optional)
    pub fn payment_rail(mut self, value: impl Into<Option<S>>) -> 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<S>) -> Self {
        self._fields.8 = value;
        self
    }
}

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

impl<St: receipt_state::State, S: BosStr> ReceiptBuilder<St, S> {
    /// Set the `transactionId` field (optional)
    pub fn transaction_id(mut self, value: impl Into<Option<S>>) -> 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<S>) -> Self {
        self._fields.10 = value;
        self
    }
}

impl<St, S: BosStr> ReceiptBuilder<St, S>
where
    St: receipt_state::State,
    St::Amount: receipt_state::IsSet,
    St::CreatedAt: receipt_state::IsSet,
    St::Currency: receipt_state::IsSet,
    St::From: receipt_state::IsSet,
    St::To: receipt_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Receipt<S> {
        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<SmolStr, Data<S>>) -> Receipt<S> {
        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()
    }
}