// @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;

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
use jacquard_common::types::string::Datetime;
use jacquard_derive::{IntoStatic, lexicon, 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;

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct RedeemTicket<'a> {
    ///Ticket redemption code
    #[serde(borrow)]
    pub code: CowStr<'a>,
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct RedeemTicketOutput<'a> {
    #[serde(borrow)]
    pub assignment: redeem_ticket::RedeemedAssignment<'a>,
    ///Success message
    #[serde(borrow)]
    pub message: CowStr<'a>,
}


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

#[serde(tag = "error", content = "message")]
#[serde(bound(deserialize = "'de: 'a"))]
pub enum RedeemTicketError<'a> {
    /// Ticket code not found
    #[serde(rename = "TicketNotFound")]
    TicketNotFound(Option<CowStr<'a>>),
    /// Ticket has already been redeemed
    #[serde(rename = "TicketAlreadyRedeemed")]
    TicketAlreadyRedeemed(Option<CowStr<'a>>),
    /// Ticket has expired
    #[serde(rename = "TicketExpired")]
    TicketExpired(Option<CowStr<'a>>),
}

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::Unknown(err) => write!(f, "Unknown error: {:?}", err),
        }
    }
}

/// Redeemed plan assignment.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct RedeemedAssignment<'a> {
    ///Plan activation timestamp
    pub activated_at: Datetime,
    ///Plan expiration timestamp
    pub expires_at: Datetime,
    ///Plan assignment ID
    #[serde(borrow)]
    pub id: CowStr<'a>,
    ///Plan ID
    #[serde(borrow)]
    pub plan_id: CowStr<'a>,
    ///Plan assignment status
    #[serde(borrow)]
    pub status: CowStr<'a>,
}

/// Response type for app.chronosky.plan.redeemTicket
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<'de> = RedeemTicketOutput<'de>;
    type Err<'de> = RedeemTicketError<'de>;
}

impl<'a> jacquard_common::xrpc::XrpcRequest for RedeemTicket<'a> {
    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 type for app.chronosky.plan.redeemTicket
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<'de> = RedeemTicket<'de>;
    type Response = RedeemTicketResponse;
}

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

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

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

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

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

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

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

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

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

impl<'a, S> RedeemedAssignmentBuilder<'a, S>
where
    S: redeemed_assignment_state::State,
    S::Id: redeemed_assignment_state::IsSet,
    S::Status: redeemed_assignment_state::IsSet,
    S::ExpiresAt: redeemed_assignment_state::IsSet,
    S::ActivatedAt: redeemed_assignment_state::IsSet,
    S::PlanId: redeemed_assignment_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> RedeemedAssignment<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> RedeemedAssignment<'a> {
        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()
    }
}