// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: com.suibari.atsumeat.transaction
//
// 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::{Did, AtUri, Cid, Datetime, UriValue};
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};
/// Definition of a transaction

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Transaction<'a> {
    pub created_at: Datetime,
    ///Flag to indicate if this is an Easy Exchange (random partner).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_easy_exchange: Option<bool>,
    ///Optional message attached to the exchange offer or completion.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub message: Option<CowStr<'a>>,
    ///The DID of the exchange partner.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub partner: Option<Did<'a>>,
    ///URI of the partner's profile, used for Constellation backlinking during the offer stage.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub ref_partner: Option<UriValue<'a>>,
    ///URI of the referencing transaction (e.g., the original Offer) when completing or rejecting.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub ref_transaction: Option<UriValue<'a>>,
    ///The current status of the transaction.
    #[serde(borrow)]
    pub status: TransactionStatus<'a>,
    ///URIs of the stickers received in this exchange (if completed).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub sticker_in: Option<Vec<UriValue<'a>>>,
    ///URIs of the stickers given in this exchange.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub sticker_out: Option<Vec<UriValue<'a>>>,
}

/// The current status of the transaction.

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TransactionStatus<'a> {
    Offered,
    Completed,
    Rejected,
    Other(CowStr<'a>),
}

impl<'a> TransactionStatus<'a> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Offered => "offered",
            Self::Completed => "completed",
            Self::Rejected => "rejected",
            Self::Other(s) => s.as_ref(),
        }
    }
}

impl<'a> From<&'a str> for TransactionStatus<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "offered" => Self::Offered,
            "completed" => Self::Completed,
            "rejected" => Self::Rejected,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for TransactionStatus<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "offered" => Self::Offered,
            "completed" => Self::Completed,
            "rejected" => Self::Rejected,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> core::fmt::Display for TransactionStatus<'a> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl<'a> AsRef<str> for TransactionStatus<'a> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<'a> serde::Serialize for TransactionStatus<'a> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de, 'a> serde::Deserialize<'de> for TransactionStatus<'a>
where
    'de: 'a,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = <&'de str>::deserialize(deserializer)?;
        Ok(Self::from(s))
    }
}

impl<'a> Default for TransactionStatus<'a> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl jacquard_common::IntoStatic for TransactionStatus<'_> {
    type Output = TransactionStatus<'static>;
    fn into_static(self) -> Self::Output {
        match self {
            TransactionStatus::Offered => TransactionStatus::Offered,
            TransactionStatus::Completed => TransactionStatus::Completed,
            TransactionStatus::Rejected => TransactionStatus::Rejected,
            TransactionStatus::Other(v) => TransactionStatus::Other(v.into_static()),
        }
    }
}

/// 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 TransactionGetRecordOutput<'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: Transaction<'a>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct TransactionRecord;
impl XrpcResp for TransactionRecord {
    const NSID: &'static str = "com.suibari.atsumeat.transaction";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = TransactionGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Transaction<'_> {
    const NSID: &'static str = "com.suibari.atsumeat.transaction";
    type Record = TransactionRecord;
}

impl Collection for TransactionRecord {
    const NSID: &'static str = "com.suibari.atsumeat.transaction";
    type Record = TransactionRecord;
}

impl<'a> LexiconSchema for Transaction<'a> {
    fn nsid() -> &'static str {
        "com.suibari.atsumeat.transaction"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_com_suibari_atsumeat_transaction()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.message {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 6400usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("message"),
                    max: 6400usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.message {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 640usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("message"),
                        max: 640usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let value = &self.status;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 64usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("status"),
                    max: 64usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod transaction_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 Status;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedAt = Unset;
        type Status = Unset;
    }
    ///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 CreatedAt = Set<members::created_at>;
        type Status = S::Status;
    }
    ///State transition - sets the `status` field to Set
    pub struct SetStatus<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetStatus<S> {}
    impl<S: State> State for SetStatus<S> {
        type CreatedAt = S::CreatedAt;
        type Status = Set<members::status>;
    }
    /// 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 `status` field
        pub struct status(());
    }
}

/// Builder for constructing an instance of this type
pub struct TransactionBuilder<'a, S: transaction_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Datetime>,
        Option<bool>,
        Option<CowStr<'a>>,
        Option<Did<'a>>,
        Option<UriValue<'a>>,
        Option<UriValue<'a>>,
        Option<TransactionStatus<'a>>,
        Option<Vec<UriValue<'a>>>,
        Option<Vec<UriValue<'a>>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Transaction<'a> {
    /// Create a new builder for this type
    pub fn new() -> TransactionBuilder<'a, transaction_state::Empty> {
        TransactionBuilder::new()
    }
}

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

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

impl<'a, S: transaction_state::State> TransactionBuilder<'a, S> {
    /// Set the `isEasyExchange` field (optional)
    pub fn is_easy_exchange(mut self, value: impl Into<Option<bool>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `isEasyExchange` field to an Option value (optional)
    pub fn maybe_is_easy_exchange(mut self, value: Option<bool>) -> Self {
        self._fields.1 = value;
        self
    }
}

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

impl<'a, S: transaction_state::State> TransactionBuilder<'a, S> {
    /// Set the `partner` field (optional)
    pub fn partner(mut self, value: impl Into<Option<Did<'a>>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `partner` field to an Option value (optional)
    pub fn maybe_partner(mut self, value: Option<Did<'a>>) -> Self {
        self._fields.3 = value;
        self
    }
}

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

impl<'a, S: transaction_state::State> TransactionBuilder<'a, S> {
    /// Set the `refTransaction` field (optional)
    pub fn ref_transaction(mut self, value: impl Into<Option<UriValue<'a>>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `refTransaction` field to an Option value (optional)
    pub fn maybe_ref_transaction(mut self, value: Option<UriValue<'a>>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<'a, S> TransactionBuilder<'a, S>
where
    S: transaction_state::State,
    S::Status: transaction_state::IsUnset,
{
    /// Set the `status` field (required)
    pub fn status(
        mut self,
        value: impl Into<TransactionStatus<'a>>,
    ) -> TransactionBuilder<'a, transaction_state::SetStatus<S>> {
        self._fields.6 = Option::Some(value.into());
        TransactionBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: transaction_state::State> TransactionBuilder<'a, S> {
    /// Set the `stickerIn` field (optional)
    pub fn sticker_in(mut self, value: impl Into<Option<Vec<UriValue<'a>>>>) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `stickerIn` field to an Option value (optional)
    pub fn maybe_sticker_in(mut self, value: Option<Vec<UriValue<'a>>>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<'a, S: transaction_state::State> TransactionBuilder<'a, S> {
    /// Set the `stickerOut` field (optional)
    pub fn sticker_out(mut self, value: impl Into<Option<Vec<UriValue<'a>>>>) -> Self {
        self._fields.8 = value.into();
        self
    }
    /// Set the `stickerOut` field to an Option value (optional)
    pub fn maybe_sticker_out(mut self, value: Option<Vec<UriValue<'a>>>) -> Self {
        self._fields.8 = value;
        self
    }
}

impl<'a, S> TransactionBuilder<'a, S>
where
    S: transaction_state::State,
    S::CreatedAt: transaction_state::IsSet,
    S::Status: transaction_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Transaction<'a> {
        Transaction {
            created_at: self._fields.0.unwrap(),
            is_easy_exchange: self._fields.1,
            message: self._fields.2,
            partner: self._fields.3,
            ref_partner: self._fields.4,
            ref_transaction: self._fields.5,
            status: self._fields.6.unwrap(),
            sticker_in: self._fields.7,
            sticker_out: self._fields.8,
            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>,
        >,
    ) -> Transaction<'a> {
        Transaction {
            created_at: self._fields.0.unwrap(),
            is_easy_exchange: self._fields.1,
            message: self._fields.2,
            partner: self._fields.3,
            ref_partner: self._fields.4,
            ref_transaction: self._fields.5,
            status: self._fields.6.unwrap(),
            sticker_in: self._fields.7,
            sticker_out: self._fields.8,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_com_suibari_atsumeat_transaction() -> 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("com.suibari.atsumeat.transaction"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(CowStr::new_static("Definition of a transaction")),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("status"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("isEasyExchange"),
                                LexObjectProperty::Boolean(LexBoolean {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("message"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Optional message attached to the exchange offer or completion.",
                                        ),
                                    ),
                                    max_length: Some(6400usize),
                                    max_graphemes: Some(640usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("partner"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("The DID of the exchange partner."),
                                    ),
                                    format: Some(LexStringFormat::Did),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("refPartner"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "URI of the partner's profile, used for Constellation backlinking during the offer stage.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Uri),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("refTransaction"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "URI of the referencing transaction (e.g., the original Offer) when completing or rejecting.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Uri),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("status"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("The current status of the transaction."),
                                    ),
                                    max_length: Some(64usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("stickerIn"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "URIs of the stickers received in this exchange (if completed).",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        format: Some(LexStringFormat::Uri),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("stickerOut"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "URIs of the stickers given in this exchange.",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        format: Some(LexStringFormat::Uri),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}