// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: app.fitsky.goal
//
// 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};
use jacquard_lexicon::lexicon::LexiconDoc;
use jacquard_lexicon::schema::LexiconSchema;

#[allow(unused_imports)]
use jacquard_lexicon::validation::{ConstraintError, ValidationPath};
use serde::{Serialize, Deserialize};
/// A fitness goal to track progress against

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "app.fitsky.goal",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Goal<S: BosStr = DefaultStr> {
    pub created_at: Datetime,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_date: Option<Datetime>,
    pub metric: GoalMetric<S>,
    pub period: GoalPeriod<S>,
    pub start_date: Datetime,
    ///Target value in base units (meters for distance, seconds for duration, seconds-per-km for pace, count for workouts)
    pub target_value: i64,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum GoalMetric<S: BosStr = DefaultStr> {
    Distance,
    Workouts,
    Duration,
    Pace,
    Other(S),
}

impl<S: BosStr> GoalMetric<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Distance => "distance",
            Self::Workouts => "workouts",
            Self::Duration => "duration",
            Self::Pace => "pace",
            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() {
            "distance" => Self::Distance,
            "workouts" => Self::Workouts,
            "duration" => Self::Duration,
            "pace" => Self::Pace,
            _ => Self::Other(s),
        }
    }
}

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

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

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

impl<S: BosStr> jacquard_common::IntoStatic for GoalMetric<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = GoalMetric<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            GoalMetric::Distance => GoalMetric::Distance,
            GoalMetric::Workouts => GoalMetric::Workouts,
            GoalMetric::Duration => GoalMetric::Duration,
            GoalMetric::Pace => GoalMetric::Pace,
            GoalMetric::Other(v) => GoalMetric::Other(v.into_static()),
        }
    }
}


#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum GoalPeriod<S: BosStr = DefaultStr> {
    Weekly,
    Monthly,
    Yearly,
    Other(S),
}

impl<S: BosStr> GoalPeriod<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Weekly => "weekly",
            Self::Monthly => "monthly",
            Self::Yearly => "yearly",
            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() {
            "weekly" => Self::Weekly,
            "monthly" => Self::Monthly,
            "yearly" => Self::Yearly,
            _ => Self::Other(s),
        }
    }
}

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

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

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

impl<S: BosStr> jacquard_common::IntoStatic for GoalPeriod<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = GoalPeriod<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            GoalPeriod::Weekly => GoalPeriod::Weekly,
            GoalPeriod::Monthly => GoalPeriod::Monthly,
            GoalPeriod::Yearly => GoalPeriod::Yearly,
            GoalPeriod::Other(v) => GoalPeriod::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 GoalGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Goal<S>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct GoalRecord;
impl XrpcResp for GoalRecord {
    const NSID: &'static str = "app.fitsky.goal";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = GoalGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Goal<S> {
    const NSID: &'static str = "app.fitsky.goal";
    type Record = GoalRecord;
}

impl Collection for GoalRecord {
    const NSID: &'static str = "app.fitsky.goal";
    type Record = GoalRecord;
}

impl<S: BosStr> LexiconSchema for Goal<S> {
    fn nsid() -> &'static str {
        "app.fitsky.goal"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_fitsky_goal()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.metric;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 64usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("metric"),
                    max: 64usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.period;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 64usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("period"),
                    max: 64usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.target_value;
            if *value < 0i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("target_value"),
                    min: 0i64,
                    actual: *value,
                });
            }
        }
        Ok(())
    }
}

pub mod goal_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 Metric;
        type Period;
        type StartDate;
        type TargetValue;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedAt = Unset;
        type Metric = Unset;
        type Period = Unset;
        type StartDate = Unset;
        type TargetValue = 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 Metric = St::Metric;
        type Period = St::Period;
        type StartDate = St::StartDate;
        type TargetValue = St::TargetValue;
    }
    ///State transition - sets the `metric` field to Set
    pub struct SetMetric<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetMetric<St> {}
    impl<St: State> State for SetMetric<St> {
        type CreatedAt = St::CreatedAt;
        type Metric = Set<members::metric>;
        type Period = St::Period;
        type StartDate = St::StartDate;
        type TargetValue = St::TargetValue;
    }
    ///State transition - sets the `period` field to Set
    pub struct SetPeriod<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetPeriod<St> {}
    impl<St: State> State for SetPeriod<St> {
        type CreatedAt = St::CreatedAt;
        type Metric = St::Metric;
        type Period = Set<members::period>;
        type StartDate = St::StartDate;
        type TargetValue = St::TargetValue;
    }
    ///State transition - sets the `start_date` field to Set
    pub struct SetStartDate<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetStartDate<St> {}
    impl<St: State> State for SetStartDate<St> {
        type CreatedAt = St::CreatedAt;
        type Metric = St::Metric;
        type Period = St::Period;
        type StartDate = Set<members::start_date>;
        type TargetValue = St::TargetValue;
    }
    ///State transition - sets the `target_value` field to Set
    pub struct SetTargetValue<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetTargetValue<St> {}
    impl<St: State> State for SetTargetValue<St> {
        type CreatedAt = St::CreatedAt;
        type Metric = St::Metric;
        type Period = St::Period;
        type StartDate = St::StartDate;
        type TargetValue = Set<members::target_value>;
    }
    /// 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 `metric` field
        pub struct metric(());
        ///Marker type for the `period` field
        pub struct period(());
        ///Marker type for the `start_date` field
        pub struct start_date(());
        ///Marker type for the `target_value` field
        pub struct target_value(());
    }
}

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

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

impl<S: BosStr> Goal<S> {
    /// Create a new builder for this type
    pub fn builder() -> GoalBuilder<goal_state::Empty, S> {
        GoalBuilder::builder()
    }
}

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

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

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

impl<St: goal_state::State, S: BosStr> GoalBuilder<St, S> {
    /// Set the `endDate` field (optional)
    pub fn end_date(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `endDate` field to an Option value (optional)
    pub fn maybe_end_date(mut self, value: Option<Datetime>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<St, S: BosStr> GoalBuilder<St, S>
where
    St: goal_state::State,
    St::Metric: goal_state::IsUnset,
{
    /// Set the `metric` field (required)
    pub fn metric(
        mut self,
        value: impl Into<GoalMetric<S>>,
    ) -> GoalBuilder<goal_state::SetMetric<St>, S> {
        self._fields.2 = Option::Some(value.into());
        GoalBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> GoalBuilder<St, S>
where
    St: goal_state::State,
    St::Period: goal_state::IsUnset,
{
    /// Set the `period` field (required)
    pub fn period(
        mut self,
        value: impl Into<GoalPeriod<S>>,
    ) -> GoalBuilder<goal_state::SetPeriod<St>, S> {
        self._fields.3 = Option::Some(value.into());
        GoalBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> GoalBuilder<St, S>
where
    St: goal_state::State,
    St::StartDate: goal_state::IsUnset,
{
    /// Set the `startDate` field (required)
    pub fn start_date(
        mut self,
        value: impl Into<Datetime>,
    ) -> GoalBuilder<goal_state::SetStartDate<St>, S> {
        self._fields.4 = Option::Some(value.into());
        GoalBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> GoalBuilder<St, S>
where
    St: goal_state::State,
    St::TargetValue: goal_state::IsUnset,
{
    /// Set the `targetValue` field (required)
    pub fn target_value(
        mut self,
        value: impl Into<i64>,
    ) -> GoalBuilder<goal_state::SetTargetValue<St>, S> {
        self._fields.5 = Option::Some(value.into());
        GoalBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> GoalBuilder<St, S>
where
    St: goal_state::State,
    St::CreatedAt: goal_state::IsSet,
    St::Metric: goal_state::IsSet,
    St::Period: goal_state::IsSet,
    St::StartDate: goal_state::IsSet,
    St::TargetValue: goal_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Goal<S> {
        Goal {
            created_at: self._fields.0.unwrap(),
            end_date: self._fields.1,
            metric: self._fields.2.unwrap(),
            period: self._fields.3.unwrap(),
            start_date: self._fields.4.unwrap(),
            target_value: self._fields.5.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>>) -> Goal<S> {
        Goal {
            created_at: self._fields.0.unwrap(),
            end_date: self._fields.1,
            metric: self._fields.2.unwrap(),
            period: self._fields.3.unwrap(),
            start_date: self._fields.4.unwrap(),
            target_value: self._fields.5.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_app_fitsky_goal() -> 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.fitsky.goal"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static("A fitness goal to track progress against"),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("metric"),
                                SmolStr::new_static("targetValue"),
                                SmolStr::new_static("period"),
                                SmolStr::new_static("startDate"),
                                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("endDate"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("metric"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(64usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("period"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(64usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("startDate"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("targetValue"),
                                LexObjectProperty::Integer(LexInteger {
                                    minimum: Some(0i64),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}