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

#[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};
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

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Goal<'a> {
    pub created_at: Datetime,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_date: Option<Datetime>,
    #[serde(borrow)]
    pub metric: GoalMetric<'a>,
    #[serde(borrow)]
    pub period: GoalPeriod<'a>,
    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,
}


#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum GoalMetric<'a> {
    Distance,
    Workouts,
    Duration,
    Pace,
    Other(CowStr<'a>),
}

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

impl<'a> From<&'a str> for GoalMetric<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "distance" => Self::Distance,
            "workouts" => Self::Workouts,
            "duration" => Self::Duration,
            "pace" => Self::Pace,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for GoalMetric<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "distance" => Self::Distance,
            "workouts" => Self::Workouts,
            "duration" => Self::Duration,
            "pace" => Self::Pace,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

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

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

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

impl jacquard_common::IntoStatic for GoalMetric<'_> {
    type Output = GoalMetric<'static>;
    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<'a> {
    Weekly,
    Monthly,
    Yearly,
    Other(CowStr<'a>),
}

impl<'a> GoalPeriod<'a> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Weekly => "weekly",
            Self::Monthly => "monthly",
            Self::Yearly => "yearly",
            Self::Other(s) => s.as_ref(),
        }
    }
}

impl<'a> From<&'a str> for GoalPeriod<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "weekly" => Self::Weekly,
            "monthly" => Self::Monthly,
            "yearly" => Self::Yearly,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for GoalPeriod<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "weekly" => Self::Weekly,
            "monthly" => Self::Monthly,
            "yearly" => Self::Yearly,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

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

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

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

impl jacquard_common::IntoStatic for GoalPeriod<'_> {
    type Output = GoalPeriod<'static>;
    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<'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: Goal<'a>,
}

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

/// 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<'de> = GoalGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Goal<'_> {
    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<'a> LexiconSchema for Goal<'a> {
    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 Metric;
        type CreatedAt;
        type TargetValue;
        type StartDate;
        type Period;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Metric = Unset;
        type CreatedAt = Unset;
        type TargetValue = Unset;
        type StartDate = Unset;
        type Period = Unset;
    }
    ///State transition - sets the `metric` field to Set
    pub struct SetMetric<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetMetric<S> {}
    impl<S: State> State for SetMetric<S> {
        type Metric = Set<members::metric>;
        type CreatedAt = S::CreatedAt;
        type TargetValue = S::TargetValue;
        type StartDate = S::StartDate;
        type Period = S::Period;
    }
    ///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 Metric = S::Metric;
        type CreatedAt = Set<members::created_at>;
        type TargetValue = S::TargetValue;
        type StartDate = S::StartDate;
        type Period = S::Period;
    }
    ///State transition - sets the `target_value` field to Set
    pub struct SetTargetValue<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetTargetValue<S> {}
    impl<S: State> State for SetTargetValue<S> {
        type Metric = S::Metric;
        type CreatedAt = S::CreatedAt;
        type TargetValue = Set<members::target_value>;
        type StartDate = S::StartDate;
        type Period = S::Period;
    }
    ///State transition - sets the `start_date` field to Set
    pub struct SetStartDate<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetStartDate<S> {}
    impl<S: State> State for SetStartDate<S> {
        type Metric = S::Metric;
        type CreatedAt = S::CreatedAt;
        type TargetValue = S::TargetValue;
        type StartDate = Set<members::start_date>;
        type Period = S::Period;
    }
    ///State transition - sets the `period` field to Set
    pub struct SetPeriod<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetPeriod<S> {}
    impl<S: State> State for SetPeriod<S> {
        type Metric = S::Metric;
        type CreatedAt = S::CreatedAt;
        type TargetValue = S::TargetValue;
        type StartDate = S::StartDate;
        type Period = Set<members::period>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `metric` field
        pub struct metric(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `target_value` field
        pub struct target_value(());
        ///Marker type for the `start_date` field
        pub struct start_date(());
        ///Marker type for the `period` field
        pub struct period(());
    }
}

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

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

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

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

impl<'a, S: goal_state::State> GoalBuilder<'a, 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<'a, S> GoalBuilder<'a, S>
where
    S: goal_state::State,
    S::Metric: goal_state::IsUnset,
{
    /// Set the `metric` field (required)
    pub fn metric(
        mut self,
        value: impl Into<GoalMetric<'a>>,
    ) -> GoalBuilder<'a, goal_state::SetMetric<S>> {
        self._fields.2 = Option::Some(value.into());
        GoalBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

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

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

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

impl<'a, S> GoalBuilder<'a, S>
where
    S: goal_state::State,
    S::Metric: goal_state::IsSet,
    S::CreatedAt: goal_state::IsSet,
    S::TargetValue: goal_state::IsSet,
    S::StartDate: goal_state::IsSet,
    S::Period: goal_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Goal<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Goal<'a> {
        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()
    }
}