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

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
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::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;

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct IntervalSchedule<'a> {
    pub seconds: i64,
    #[serde(borrow)]
    pub r#type: CowStr<'a>,
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Job<'a> {
    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>,
    #[serde(borrow)]
    pub instructions: CowStr<'a>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_run: Option<Datetime>,
    #[serde(borrow)]
    pub name: CowStr<'a>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_run: Option<Datetime>,
    #[serde(borrow)]
    pub schedule: JobSchedule<'a>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub status: Option<JobStatus<'a>>,
}


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


#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum JobStatus<'a> {
    Pending,
    Running,
    Completed,
    Failed,
    Other(CowStr<'a>),
}

impl<'a> JobStatus<'a> {
    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(),
        }
    }
}

impl<'a> From<&'a str> for JobStatus<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "pending" => Self::Pending,
            "running" => Self::Running,
            "completed" => Self::Completed,
            "failed" => Self::Failed,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for JobStatus<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "pending" => Self::Pending,
            "running" => Self::Running,
            "completed" => Self::Completed,
            "failed" => Self::Failed,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

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

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

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

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

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

impl jacquard_common::IntoStatic for JobStatus<'_> {
    type Output = JobStatus<'static>;
    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<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub cid: Option<Cid<'a>>,
    #[serde(borrow)]
    pub uri: AtUri<'a>,
    #[serde(borrow)]
    pub value: Job<'a>,
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct OnceSchedule<'a> {
    pub run_at: Datetime,
    #[serde(borrow)]
    pub r#type: CowStr<'a>,
}

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

impl<'a> LexiconSchema for IntervalSchedule<'a> {
    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<'de> = JobGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Job<'_> {
    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<'a> LexiconSchema for Job<'a> {
    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<'a> LexiconSchema for OnceSchedule<'a> {
    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<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetSeconds<S> {}
    impl<S: State> State for SetSeconds<S> {
        type Seconds = Set<members::seconds>;
        type Type = S::Type;
    }
    ///State transition - sets the `type` field to Set
    pub struct SetType<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetType<S> {}
    impl<S: State> State for SetType<S> {
        type Seconds = S::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<'a, S: interval_schedule_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (Option<i64>, Option<CowStr<'a>>),
    _lifetime: PhantomData<&'a ()>,
}

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

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

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

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

impl<'a, S> IntervalScheduleBuilder<'a, S>
where
    S: interval_schedule_state::State,
    S::Seconds: interval_schedule_state::IsSet,
    S::Type: interval_schedule_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> IntervalSchedule<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> IntervalSchedule<'a> {
        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 Name;
        type Schedule;
        type Instructions;
        type CreatedAt;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Name = Unset;
        type Schedule = Unset;
        type Instructions = Unset;
        type CreatedAt = Unset;
    }
    ///State transition - sets the `name` field to Set
    pub struct SetName<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetName<S> {}
    impl<S: State> State for SetName<S> {
        type Name = Set<members::name>;
        type Schedule = S::Schedule;
        type Instructions = S::Instructions;
        type CreatedAt = S::CreatedAt;
    }
    ///State transition - sets the `schedule` field to Set
    pub struct SetSchedule<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetSchedule<S> {}
    impl<S: State> State for SetSchedule<S> {
        type Name = S::Name;
        type Schedule = Set<members::schedule>;
        type Instructions = S::Instructions;
        type CreatedAt = S::CreatedAt;
    }
    ///State transition - sets the `instructions` field to Set
    pub struct SetInstructions<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetInstructions<S> {}
    impl<S: State> State for SetInstructions<S> {
        type Name = S::Name;
        type Schedule = S::Schedule;
        type Instructions = Set<members::instructions>;
        type CreatedAt = S::CreatedAt;
    }
    ///State transition - sets the `created_at` field to Set
    pub struct SetCreatedAt<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetCreatedAt<S> {}
    impl<S: State> State for SetCreatedAt<S> {
        type Name = S::Name;
        type Schedule = S::Schedule;
        type Instructions = S::Instructions;
        type CreatedAt = Set<members::created_at>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `name` field
        pub struct name(());
        ///Marker type for the `schedule` field
        pub struct schedule(());
        ///Marker type for the `instructions` field
        pub struct instructions(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
    }
}

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

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

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

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

impl<'a, S: job_state::State> JobBuilder<'a, 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<'a, S> JobBuilder<'a, S>
where
    S: job_state::State,
    S::Instructions: job_state::IsUnset,
{
    /// Set the `instructions` field (required)
    pub fn instructions(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> JobBuilder<'a, job_state::SetInstructions<S>> {
        self._fields.2 = Option::Some(value.into());
        JobBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: job_state::State> JobBuilder<'a, 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<'a, S> JobBuilder<'a, S>
where
    S: job_state::State,
    S::Name: job_state::IsUnset,
{
    /// Set the `name` field (required)
    pub fn name(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> JobBuilder<'a, job_state::SetName<S>> {
        self._fields.4 = Option::Some(value.into());
        JobBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: job_state::State> JobBuilder<'a, 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<'a, S> JobBuilder<'a, S>
where
    S: job_state::State,
    S::Schedule: job_state::IsUnset,
{
    /// Set the `schedule` field (required)
    pub fn schedule(
        mut self,
        value: impl Into<JobSchedule<'a>>,
    ) -> JobBuilder<'a, job_state::SetSchedule<S>> {
        self._fields.6 = Option::Some(value.into());
        JobBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: job_state::State> JobBuilder<'a, S> {
    /// Set the `status` field (optional)
    pub fn status(mut self, value: impl Into<Option<JobStatus<'a>>>) -> 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<'a>>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<'a, S> JobBuilder<'a, S>
where
    S: job_state::State,
    S::Name: job_state::IsSet,
    S::Schedule: job_state::IsSet,
    S::Instructions: job_state::IsSet,
    S::CreatedAt: job_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Job<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Job<'a> {
        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<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetRunAt<S> {}
    impl<S: State> State for SetRunAt<S> {
        type RunAt = Set<members::run_at>;
        type Type = S::Type;
    }
    ///State transition - sets the `type` field to Set
    pub struct SetType<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetType<S> {}
    impl<S: State> State for SetType<S> {
        type RunAt = S::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<'a, S: once_schedule_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (Option<Datetime>, Option<CowStr<'a>>),
    _lifetime: PhantomData<&'a ()>,
}

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

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

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

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

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