// @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, 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::{Did, AtUri, Cid, Datetime, UriValue};
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};
/// Definition of a transaction

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "com.suibari.atsumeat.transaction",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Transaction<S: BosStr = DefaultStr> {
    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")]
    pub message: Option<S>,
    ///The DID of the exchange partner.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub partner: Option<Did<S>>,
    ///URI of the partner's profile, used for Constellation backlinking during the offer stage.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ref_partner: Option<UriValue<S>>,
    ///URI of the referencing transaction (e.g., the original Offer) when completing or rejecting.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ref_transaction: Option<UriValue<S>>,
    ///The current status of the transaction.
    pub status: TransactionStatus<S>,
    ///URIs of the stickers received in this exchange (if completed).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sticker_in: Option<Vec<UriValue<S>>>,
    ///URIs of the stickers given in this exchange.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sticker_out: Option<Vec<UriValue<S>>>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// The current status of the transaction.

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TransactionStatus<S: BosStr = DefaultStr> {
    Offered,
    Completed,
    Rejected,
    Other(S),
}

impl<S: BosStr> TransactionStatus<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Offered => "offered",
            Self::Completed => "completed",
            Self::Rejected => "rejected",
            Self::Other(s) => s.as_ref(),
        }
    }
    /// Construct from a string-like value, matching known values.
    pub fn from_value(s: S) -> Self {
        match s.as_ref() {
            "offered" => Self::Offered,
            "completed" => Self::Completed,
            "rejected" => Self::Rejected,
            _ => Self::Other(s),
        }
    }
}

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

impl<S: BosStr> AsRef<str> for TransactionStatus<S> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

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

impl<'de, S: Deserialize<'de> + BosStr> Deserialize<'de> for TransactionStatus<S> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = S::deserialize(deserializer)?;
        Ok(Self::from_value(s))
    }
}

impl<S: BosStr + Default> Default for TransactionStatus<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for TransactionStatus<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = TransactionStatus<S::Output>;
    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<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Transaction<S>,
}

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

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

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

impl<S: BosStr> Collection for Transaction<S> {
    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<S: BosStr> LexiconSchema for Transaction<S> {
    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<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 Status = St::Status;
    }
    ///State transition - sets the `status` field to Set
    pub struct SetStatus<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetStatus<St> {}
    impl<St: State> State for SetStatus<St> {
        type CreatedAt = St::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<St: transaction_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Datetime>,
        Option<bool>,
        Option<S>,
        Option<Did<S>>,
        Option<UriValue<S>>,
        Option<UriValue<S>>,
        Option<TransactionStatus<S>>,
        Option<Vec<UriValue<S>>>,
        Option<Vec<UriValue<S>>>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

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

impl<St: transaction_state::State, S: BosStr> TransactionBuilder<St, 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<St: transaction_state::State, S: BosStr> TransactionBuilder<St, S> {
    /// Set the `message` field (optional)
    pub fn message(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `message` field to an Option value (optional)
    pub fn maybe_message(mut self, value: Option<S>) -> Self {
        self._fields.2 = value;
        self
    }
}

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

impl<St: transaction_state::State, S: BosStr> TransactionBuilder<St, S> {
    /// Set the `refPartner` field (optional)
    pub fn ref_partner(mut self, value: impl Into<Option<UriValue<S>>>) -> 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<S>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St: transaction_state::State, S: BosStr> TransactionBuilder<St, S> {
    /// Set the `refTransaction` field (optional)
    pub fn ref_transaction(mut self, value: impl Into<Option<UriValue<S>>>) -> 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<S>>) -> Self {
        self._fields.5 = value;
        self
    }
}

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

impl<St: transaction_state::State, S: BosStr> TransactionBuilder<St, S> {
    /// Set the `stickerIn` field (optional)
    pub fn sticker_in(mut self, value: impl Into<Option<Vec<UriValue<S>>>>) -> 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<S>>>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<St: transaction_state::State, S: BosStr> TransactionBuilder<St, S> {
    /// Set the `stickerOut` field (optional)
    pub fn sticker_out(mut self, value: impl Into<Option<Vec<UriValue<S>>>>) -> 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<S>>>) -> Self {
        self._fields.8 = value;
        self
    }
}

impl<St, S: BosStr> TransactionBuilder<St, S>
where
    St: transaction_state::State,
    St::CreatedAt: transaction_state::IsSet,
    St::Status: transaction_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Transaction<S> {
        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<SmolStr, Data<S>>,
    ) -> Transaction<S> {
        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()
    }
}