// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: diy.razorgirl.winter.job
//
// 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, 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::diy_razorgirl::winter::job;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct IntervalSchedule<S: BosStr = DefaultStr> {
    pub seconds: i64,
    pub r#type: 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",
    rename = "diy.razorgirl.winter.job",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Job<S: BosStr = DefaultStr> {
    pub created_at: Datetime,
    /// Defaults to `0`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default = "_default_job_failure_count")]
    pub failure_count: Option<i64>,
    pub instructions: S,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_run: Option<Datetime>,
    pub name: S,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_run: Option<Datetime>,
    pub schedule: JobSchedule<S>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<JobStatus<S>>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub enum JobSchedule<S: BosStr = DefaultStr> {
    #[serde(rename = "diy.razorgirl.winter.job#onceSchedule")]
    OnceSchedule(Box<job::OnceSchedule<S>>),
    #[serde(rename = "diy.razorgirl.winter.job#intervalSchedule")]
    IntervalSchedule(Box<job::IntervalSchedule<S>>),
}


#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum JobStatus<S: BosStr = DefaultStr> {
    Pending,
    Running,
    Completed,
    Failed,
    Other(S),
}

impl<S: BosStr> JobStatus<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Pending => "pending",
            Self::Running => "running",
            Self::Completed => "completed",
            Self::Failed => "failed",
            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() {
            "pending" => Self::Pending,
            "running" => Self::Running,
            "completed" => Self::Completed,
            "failed" => Self::Failed,
            _ => Self::Other(s),
        }
    }
}

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

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

impl<S: BosStr> Serialize for JobStatus<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 JobStatus<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 JobStatus<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for JobStatus<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = JobStatus<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            JobStatus::Pending => JobStatus::Pending,
            JobStatus::Running => JobStatus::Running,
            JobStatus::Completed => JobStatus::Completed,
            JobStatus::Failed => JobStatus::Failed,
            JobStatus::Other(v) => JobStatus::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 JobGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Job<S>,
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct OnceSchedule<S: BosStr = DefaultStr> {
    pub run_at: Datetime,
    pub r#type: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

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

impl<S: BosStr> LexiconSchema for IntervalSchedule<S> {
    fn nsid() -> &'static str {
        "diy.razorgirl.winter.job"
    }
    fn def_name() -> &'static str {
        "intervalSchedule"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_diy_razorgirl_winter_job()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

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

#[derive(Debug, Serialize, Deserialize)]
pub struct JobRecord;
impl XrpcResp for JobRecord {
    const NSID: &'static str = "diy.razorgirl.winter.job";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = JobGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Job<S> {
    const NSID: &'static str = "diy.razorgirl.winter.job";
    type Record = JobRecord;
}

impl Collection for JobRecord {
    const NSID: &'static str = "diy.razorgirl.winter.job";
    type Record = JobRecord;
}

impl<S: BosStr> LexiconSchema for Job<S> {
    fn nsid() -> &'static str {
        "diy.razorgirl.winter.job"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_diy_razorgirl_winter_job()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.instructions;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 50000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("instructions"),
                    max: 50000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.name;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 128usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("name"),
                    max: 128usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for OnceSchedule<S> {
    fn nsid() -> &'static str {
        "diy.razorgirl.winter.job"
    }
    fn def_name() -> &'static str {
        "onceSchedule"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_diy_razorgirl_winter_job()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

pub mod interval_schedule_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 Seconds;
        type Type;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Seconds = Unset;
        type Type = Unset;
    }
    ///State transition - sets the `seconds` field to Set
    pub struct SetSeconds<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetSeconds<St> {}
    impl<St: State> State for SetSeconds<St> {
        type Seconds = Set<members::seconds>;
        type Type = St::Type;
    }
    ///State transition - sets the `type` field to Set
    pub struct SetType<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetType<St> {}
    impl<St: State> State for SetType<St> {
        type Seconds = St::Seconds;
        type Type = Set<members::r#type>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `seconds` field
        pub struct seconds(());
        ///Marker type for the `type` field
        pub struct r#type(());
    }
}

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

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

impl<S: BosStr> IntervalSchedule<S> {
    /// Create a new builder for this type
    pub fn builder() -> IntervalScheduleBuilder<interval_schedule_state::Empty, S> {
        IntervalScheduleBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> IntervalScheduleBuilder<St, S>
where
    St: interval_schedule_state::State,
    St::Seconds: interval_schedule_state::IsUnset,
{
    /// Set the `seconds` field (required)
    pub fn seconds(
        mut self,
        value: impl Into<i64>,
    ) -> IntervalScheduleBuilder<interval_schedule_state::SetSeconds<St>, S> {
        self._fields.0 = Option::Some(value.into());
        IntervalScheduleBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> IntervalScheduleBuilder<St, S>
where
    St: interval_schedule_state::State,
    St::Type: interval_schedule_state::IsUnset,
{
    /// Set the `type` field (required)
    pub fn r#type(
        mut self,
        value: impl Into<S>,
    ) -> IntervalScheduleBuilder<interval_schedule_state::SetType<St>, S> {
        self._fields.1 = Option::Some(value.into());
        IntervalScheduleBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> IntervalScheduleBuilder<St, S>
where
    St: interval_schedule_state::State,
    St::Seconds: interval_schedule_state::IsSet,
    St::Type: interval_schedule_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> IntervalSchedule<S> {
        IntervalSchedule {
            seconds: self._fields.0.unwrap(),
            r#type: self._fields.1.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>>,
    ) -> IntervalSchedule<S> {
        IntervalSchedule {
            seconds: self._fields.0.unwrap(),
            r#type: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_diy_razorgirl_winter_job() -> 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("diy.razorgirl.winter.job"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("intervalSchedule"),
                LexUserType::Object(LexObject {
                    required: Some(
                        vec![SmolStr::new_static("type"), SmolStr::new_static("seconds")],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("seconds"),
                            LexObjectProperty::Integer(LexInteger {
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("type"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("name"),
                                SmolStr::new_static("instructions"),
                                SmolStr::new_static("schedule"),
                                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("failureCount"),
                                LexObjectProperty::Integer(LexInteger {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("instructions"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(50000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("lastRun"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("name"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(128usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("nextRun"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("schedule"),
                                LexObjectProperty::Union(LexRefUnion {
                                    refs: vec![
                                        CowStr::new_static("#onceSchedule"),
                                        CowStr::new_static("#intervalSchedule")
                                    ],
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("status"),
                                LexObjectProperty::String(LexString {
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("onceSchedule"),
                LexUserType::Object(LexObject {
                    required: Some(
                        vec![SmolStr::new_static("type"), SmolStr::new_static("runAt")],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("runAt"),
                            LexObjectProperty::String(LexString {
                                format: Some(LexStringFormat::Datetime),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("type"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

fn _default_job_failure_count() -> Option<i64> {
    Some(0i64)
}

pub mod job_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 Instructions;
        type Name;
        type Schedule;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedAt = Unset;
        type Instructions = Unset;
        type Name = Unset;
        type Schedule = 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 Instructions = St::Instructions;
        type Name = St::Name;
        type Schedule = St::Schedule;
    }
    ///State transition - sets the `instructions` field to Set
    pub struct SetInstructions<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetInstructions<St> {}
    impl<St: State> State for SetInstructions<St> {
        type CreatedAt = St::CreatedAt;
        type Instructions = Set<members::instructions>;
        type Name = St::Name;
        type Schedule = St::Schedule;
    }
    ///State transition - sets the `name` field to Set
    pub struct SetName<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetName<St> {}
    impl<St: State> State for SetName<St> {
        type CreatedAt = St::CreatedAt;
        type Instructions = St::Instructions;
        type Name = Set<members::name>;
        type Schedule = St::Schedule;
    }
    ///State transition - sets the `schedule` field to Set
    pub struct SetSchedule<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetSchedule<St> {}
    impl<St: State> State for SetSchedule<St> {
        type CreatedAt = St::CreatedAt;
        type Instructions = St::Instructions;
        type Name = St::Name;
        type Schedule = Set<members::schedule>;
    }
    /// 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 `instructions` field
        pub struct instructions(());
        ///Marker type for the `name` field
        pub struct name(());
        ///Marker type for the `schedule` field
        pub struct schedule(());
    }
}

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

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

impl<S: BosStr> Job<S> {
    /// Create a new builder for this type
    pub fn builder() -> JobBuilder<job_state::Empty, S> {
        JobBuilder::builder()
    }
}

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

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

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

impl<St: job_state::State, S: BosStr> JobBuilder<St, S> {
    /// Set the `failureCount` field (optional)
    pub fn failure_count(mut self, value: impl Into<Option<i64>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `failureCount` field to an Option value (optional)
    pub fn maybe_failure_count(mut self, value: Option<i64>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<St, S: BosStr> JobBuilder<St, S>
where
    St: job_state::State,
    St::Instructions: job_state::IsUnset,
{
    /// Set the `instructions` field (required)
    pub fn instructions(
        mut self,
        value: impl Into<S>,
    ) -> JobBuilder<job_state::SetInstructions<St>, S> {
        self._fields.2 = Option::Some(value.into());
        JobBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: job_state::State, S: BosStr> JobBuilder<St, S> {
    /// Set the `lastRun` field (optional)
    pub fn last_run(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `lastRun` field to an Option value (optional)
    pub fn maybe_last_run(mut self, value: Option<Datetime>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St, S: BosStr> JobBuilder<St, S>
where
    St: job_state::State,
    St::Name: job_state::IsUnset,
{
    /// Set the `name` field (required)
    pub fn name(mut self, value: impl Into<S>) -> JobBuilder<job_state::SetName<St>, S> {
        self._fields.4 = Option::Some(value.into());
        JobBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: job_state::State, S: BosStr> JobBuilder<St, S> {
    /// Set the `nextRun` field (optional)
    pub fn next_run(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `nextRun` field to an Option value (optional)
    pub fn maybe_next_run(mut self, value: Option<Datetime>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<St, S: BosStr> JobBuilder<St, S>
where
    St: job_state::State,
    St::Schedule: job_state::IsUnset,
{
    /// Set the `schedule` field (required)
    pub fn schedule(
        mut self,
        value: impl Into<JobSchedule<S>>,
    ) -> JobBuilder<job_state::SetSchedule<St>, S> {
        self._fields.6 = Option::Some(value.into());
        JobBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: job_state::State, S: BosStr> JobBuilder<St, S> {
    /// Set the `status` field (optional)
    pub fn status(mut self, value: impl Into<Option<JobStatus<S>>>) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `status` field to an Option value (optional)
    pub fn maybe_status(mut self, value: Option<JobStatus<S>>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<St, S: BosStr> JobBuilder<St, S>
where
    St: job_state::State,
    St::CreatedAt: job_state::IsSet,
    St::Instructions: job_state::IsSet,
    St::Name: job_state::IsSet,
    St::Schedule: job_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Job<S> {
        Job {
            created_at: self._fields.0.unwrap(),
            failure_count: self._fields.1.or_else(|| Some(0i64)),
            instructions: self._fields.2.unwrap(),
            last_run: self._fields.3,
            name: self._fields.4.unwrap(),
            next_run: self._fields.5,
            schedule: self._fields.6.unwrap(),
            status: self._fields.7,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(self, extra_data: BTreeMap<SmolStr, Data<S>>) -> Job<S> {
        Job {
            created_at: self._fields.0.unwrap(),
            failure_count: self._fields.1.or_else(|| Some(0i64)),
            instructions: self._fields.2.unwrap(),
            last_run: self._fields.3,
            name: self._fields.4.unwrap(),
            next_run: self._fields.5,
            schedule: self._fields.6.unwrap(),
            status: self._fields.7,
            extra_data: Some(extra_data),
        }
    }
}

pub mod once_schedule_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 RunAt;
        type Type;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type RunAt = Unset;
        type Type = Unset;
    }
    ///State transition - sets the `run_at` field to Set
    pub struct SetRunAt<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetRunAt<St> {}
    impl<St: State> State for SetRunAt<St> {
        type RunAt = Set<members::run_at>;
        type Type = St::Type;
    }
    ///State transition - sets the `type` field to Set
    pub struct SetType<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetType<St> {}
    impl<St: State> State for SetType<St> {
        type RunAt = St::RunAt;
        type Type = Set<members::r#type>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `run_at` field
        pub struct run_at(());
        ///Marker type for the `type` field
        pub struct r#type(());
    }
}

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

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

impl<S: BosStr> OnceSchedule<S> {
    /// Create a new builder for this type
    pub fn builder() -> OnceScheduleBuilder<once_schedule_state::Empty, S> {
        OnceScheduleBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> OnceScheduleBuilder<St, S>
where
    St: once_schedule_state::State,
    St::RunAt: once_schedule_state::IsUnset,
{
    /// Set the `runAt` field (required)
    pub fn run_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> OnceScheduleBuilder<once_schedule_state::SetRunAt<St>, S> {
        self._fields.0 = Option::Some(value.into());
        OnceScheduleBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> OnceScheduleBuilder<St, S>
where
    St: once_schedule_state::State,
    St::Type: once_schedule_state::IsUnset,
{
    /// Set the `type` field (required)
    pub fn r#type(
        mut self,
        value: impl Into<S>,
    ) -> OnceScheduleBuilder<once_schedule_state::SetType<St>, S> {
        self._fields.1 = Option::Some(value.into());
        OnceScheduleBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> OnceScheduleBuilder<St, S>
where
    St: once_schedule_state::State,
    St::RunAt: once_schedule_state::IsSet,
    St::Type: once_schedule_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> OnceSchedule<S> {
        OnceSchedule {
            run_at: self._fields.0.unwrap(),
            r#type: self._fields.1.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>>,
    ) -> OnceSchedule<S> {
        OnceSchedule {
            run_at: self._fields.0.unwrap(),
            r#type: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}