// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: app.chronosky.plan.redeemTicket
//
// 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::string::Datetime;
use jacquard_common::types::value::Data;
use jacquard_derive::{IntoStatic, open_union};
use jacquard_lexicon::lexicon::LexiconDoc;
use jacquard_lexicon::schema::LexiconSchema;

#[allow(unused_imports)]
use jacquard_lexicon::validation::{ConstraintError, ValidationPath};
use serde::{Serialize, Deserialize};
use crate::app_chronosky::plan::redeem_ticket;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct RedeemTicket<S: BosStr = DefaultStr> {
    ///Ticket redemption code
    pub code: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct RedeemTicketOutput<S: BosStr = DefaultStr> {
    pub assignment: redeem_ticket::RedeemedAssignment<S>,
    ///Success message
    pub message: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


#[derive(
    Serialize,
    Deserialize,
    Debug,
    Clone,
    PartialEq,
    Eq,
    thiserror::Error,
    miette::Diagnostic
)]

#[serde(tag = "error", content = "message")]
pub enum RedeemTicketError {
    /// Ticket code not found
    #[serde(rename = "TicketNotFound")]
    TicketNotFound(Option<SmolStr>),
    /// Ticket has already been redeemed
    #[serde(rename = "TicketAlreadyRedeemed")]
    TicketAlreadyRedeemed(Option<SmolStr>),
    /// Ticket has expired
    #[serde(rename = "TicketExpired")]
    TicketExpired(Option<SmolStr>),
    /// Catch-all for unknown error codes.
    #[serde(untagged)]
    Other { error: SmolStr, message: Option<SmolStr> },
}

impl core::fmt::Display for RedeemTicketError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::TicketNotFound(msg) => {
                write!(f, "TicketNotFound")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::TicketAlreadyRedeemed(msg) => {
                write!(f, "TicketAlreadyRedeemed")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::TicketExpired(msg) => {
                write!(f, "TicketExpired")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::Other { error, message } => {
                write!(f, "{}", error)?;
                if let Some(msg) = message {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
        }
    }
}

/// Redeemed plan assignment.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct RedeemedAssignment<S: BosStr = DefaultStr> {
    ///Plan activation timestamp
    pub activated_at: Datetime,
    ///Plan expiration timestamp
    pub expires_at: Datetime,
    ///Plan assignment ID
    pub id: S,
    ///Plan ID
    pub plan_id: S,
    ///Plan assignment status
    pub status: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/** Response marker for the `app.chronosky.plan.redeemTicket` procedure.

Implements `jacquard_common::xrpc::XrpcResp`; successful bodies decode as `Self::Output<S>`, which is `RedeemTicketOutput<S>` for this endpoint.*/
pub struct RedeemTicketResponse;
impl jacquard_common::xrpc::XrpcResp for RedeemTicketResponse {
    const NSID: &'static str = "app.chronosky.plan.redeemTicket";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = RedeemTicketOutput<S>;
    type Err = RedeemTicketError;
}

impl<S: BosStr> jacquard_common::xrpc::XrpcRequest for RedeemTicket<S> {
    const NSID: &'static str = "app.chronosky.plan.redeemTicket";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Procedure(
        "application/json",
    );
    type Response = RedeemTicketResponse;
}

/** Endpoint marker for the `app.chronosky.plan.redeemTicket` procedure.

Path: `/xrpc/app.chronosky.plan.redeemTicket`. The request payload type is `RedeemTicket<S>`; send that request with `jacquard::Client` or use this marker through lower-level `XrpcEndpoint` APIs.*/
pub struct RedeemTicketRequest;
impl jacquard_common::xrpc::XrpcEndpoint for RedeemTicketRequest {
    const PATH: &'static str = "/xrpc/app.chronosky.plan.redeemTicket";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Procedure(
        "application/json",
    );
    type Request<S: BosStr> = RedeemTicket<S>;
    type Response = RedeemTicketResponse;
}

impl<S: BosStr> LexiconSchema for RedeemedAssignment<S> {
    fn nsid() -> &'static str {
        "app.chronosky.plan.redeemTicket"
    }
    fn def_name() -> &'static str {
        "redeemedAssignment"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_chronosky_plan_redeemTicket()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.id;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 100usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("id"),
                    max: 100usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.plan_id;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 100usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("plan_id"),
                    max: 100usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.status;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 20usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("status"),
                    max: 20usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod redeemed_assignment_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 ActivatedAt;
        type ExpiresAt;
        type Id;
        type PlanId;
        type Status;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type ActivatedAt = Unset;
        type ExpiresAt = Unset;
        type Id = Unset;
        type PlanId = Unset;
        type Status = Unset;
    }
    ///State transition - sets the `activated_at` field to Set
    pub struct SetActivatedAt<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetActivatedAt<St> {}
    impl<St: State> State for SetActivatedAt<St> {
        type ActivatedAt = Set<members::activated_at>;
        type ExpiresAt = St::ExpiresAt;
        type Id = St::Id;
        type PlanId = St::PlanId;
        type Status = St::Status;
    }
    ///State transition - sets the `expires_at` field to Set
    pub struct SetExpiresAt<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetExpiresAt<St> {}
    impl<St: State> State for SetExpiresAt<St> {
        type ActivatedAt = St::ActivatedAt;
        type ExpiresAt = Set<members::expires_at>;
        type Id = St::Id;
        type PlanId = St::PlanId;
        type Status = St::Status;
    }
    ///State transition - sets the `id` field to Set
    pub struct SetId<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetId<St> {}
    impl<St: State> State for SetId<St> {
        type ActivatedAt = St::ActivatedAt;
        type ExpiresAt = St::ExpiresAt;
        type Id = Set<members::id>;
        type PlanId = St::PlanId;
        type Status = St::Status;
    }
    ///State transition - sets the `plan_id` field to Set
    pub struct SetPlanId<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetPlanId<St> {}
    impl<St: State> State for SetPlanId<St> {
        type ActivatedAt = St::ActivatedAt;
        type ExpiresAt = St::ExpiresAt;
        type Id = St::Id;
        type PlanId = Set<members::plan_id>;
        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 ActivatedAt = St::ActivatedAt;
        type ExpiresAt = St::ExpiresAt;
        type Id = St::Id;
        type PlanId = St::PlanId;
        type Status = Set<members::status>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `activated_at` field
        pub struct activated_at(());
        ///Marker type for the `expires_at` field
        pub struct expires_at(());
        ///Marker type for the `id` field
        pub struct id(());
        ///Marker type for the `plan_id` field
        pub struct plan_id(());
        ///Marker type for the `status` field
        pub struct status(());
    }
}

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

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

impl<S: BosStr> RedeemedAssignment<S> {
    /// Create a new builder for this type
    pub fn builder() -> RedeemedAssignmentBuilder<redeemed_assignment_state::Empty, S> {
        RedeemedAssignmentBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> RedeemedAssignmentBuilder<St, S>
where
    St: redeemed_assignment_state::State,
    St::ActivatedAt: redeemed_assignment_state::IsUnset,
{
    /// Set the `activatedAt` field (required)
    pub fn activated_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> RedeemedAssignmentBuilder<redeemed_assignment_state::SetActivatedAt<St>, S> {
        self._fields.0 = Option::Some(value.into());
        RedeemedAssignmentBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> RedeemedAssignmentBuilder<St, S>
where
    St: redeemed_assignment_state::State,
    St::ExpiresAt: redeemed_assignment_state::IsUnset,
{
    /// Set the `expiresAt` field (required)
    pub fn expires_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> RedeemedAssignmentBuilder<redeemed_assignment_state::SetExpiresAt<St>, S> {
        self._fields.1 = Option::Some(value.into());
        RedeemedAssignmentBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> RedeemedAssignmentBuilder<St, S>
where
    St: redeemed_assignment_state::State,
    St::Id: redeemed_assignment_state::IsUnset,
{
    /// Set the `id` field (required)
    pub fn id(
        mut self,
        value: impl Into<S>,
    ) -> RedeemedAssignmentBuilder<redeemed_assignment_state::SetId<St>, S> {
        self._fields.2 = Option::Some(value.into());
        RedeemedAssignmentBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> RedeemedAssignmentBuilder<St, S>
where
    St: redeemed_assignment_state::State,
    St::PlanId: redeemed_assignment_state::IsUnset,
{
    /// Set the `planId` field (required)
    pub fn plan_id(
        mut self,
        value: impl Into<S>,
    ) -> RedeemedAssignmentBuilder<redeemed_assignment_state::SetPlanId<St>, S> {
        self._fields.3 = Option::Some(value.into());
        RedeemedAssignmentBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

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

impl<St, S: BosStr> RedeemedAssignmentBuilder<St, S>
where
    St: redeemed_assignment_state::State,
    St::ActivatedAt: redeemed_assignment_state::IsSet,
    St::ExpiresAt: redeemed_assignment_state::IsSet,
    St::Id: redeemed_assignment_state::IsSet,
    St::PlanId: redeemed_assignment_state::IsSet,
    St::Status: redeemed_assignment_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> RedeemedAssignment<S> {
        RedeemedAssignment {
            activated_at: self._fields.0.unwrap(),
            expires_at: self._fields.1.unwrap(),
            id: self._fields.2.unwrap(),
            plan_id: self._fields.3.unwrap(),
            status: self._fields.4.unwrap(),
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(
        self,
        extra_data: BTreeMap<SmolStr, Data<S>>,
    ) -> RedeemedAssignment<S> {
        RedeemedAssignment {
            activated_at: self._fields.0.unwrap(),
            expires_at: self._fields.1.unwrap(),
            id: self._fields.2.unwrap(),
            plan_id: self._fields.3.unwrap(),
            status: self._fields.4.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_app_chronosky_plan_redeemTicket() -> 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("app.chronosky.plan.redeemTicket"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::XrpcProcedure(LexXrpcProcedure {
                    input: Some(LexXrpcBody {
                        encoding: CowStr::new_static("application/json"),
                        schema: Some(
                            LexXrpcBodySchema::Object(LexObject {
                                required: Some(vec![SmolStr::new_static("code")]),
                                properties: {
                                    #[allow(unused_mut)]
                                    let mut map = BTreeMap::new();
                                    map.insert(
                                        SmolStr::new_static("code"),
                                        LexObjectProperty::String(LexString {
                                            description: Some(
                                                CowStr::new_static("Ticket redemption code"),
                                            ),
                                            min_length: Some(1usize),
                                            max_length: Some(100usize),
                                            ..Default::default()
                                        }),
                                    );
                                    map
                                },
                                ..Default::default()
                            }),
                        ),
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("redeemedAssignment"),
                LexUserType::Object(LexObject {
                    description: Some(CowStr::new_static("Redeemed plan assignment.")),
                    required: Some(
                        vec![
                            SmolStr::new_static("id"), SmolStr::new_static("planId"),
                            SmolStr::new_static("activatedAt"),
                            SmolStr::new_static("expiresAt"),
                            SmolStr::new_static("status")
                        ],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("activatedAt"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Plan activation timestamp"),
                                ),
                                format: Some(LexStringFormat::Datetime),
                                max_length: Some(100usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("expiresAt"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Plan expiration timestamp"),
                                ),
                                format: Some(LexStringFormat::Datetime),
                                max_length: Some(100usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("id"),
                            LexObjectProperty::String(LexString {
                                description: Some(CowStr::new_static("Plan assignment ID")),
                                max_length: Some(100usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("planId"),
                            LexObjectProperty::String(LexString {
                                description: Some(CowStr::new_static("Plan ID")),
                                max_length: Some(100usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("status"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Plan assignment status"),
                                ),
                                max_length: Some(20usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}