// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: garden.goals.completion
//
// 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::blob::BlobRef;
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 record of completing a goal on a specific day.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Completion<'a> {
    ///Timestamp when the completion was recorded
    pub completed_at: Datetime,
    ///Day of the completion (1-31)
    pub day: i64,
    ///UUID of the goal this completion belongs to
    #[serde(borrow)]
    pub goal_id: CowStr<'a>,
    ///AT Protocol URI reference to the goal record
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub goal_uri: Option<AtUri<'a>>,
    ///Month of the completion (1-12)
    pub month: i64,
    ///Optional notes for this completion
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub notes: Option<CowStr<'a>>,
    ///Optional photo for this completion
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub photo_blob: Option<BlobRef<'a>>,
    ///Sequence number for countable goals
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sequence_num: Option<i64>,
    ///Year of the completion
    pub year: i64,
}

/// 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 CompletionGetRecordOutput<'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: Completion<'a>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct CompletionRecord;
impl XrpcResp for CompletionRecord {
    const NSID: &'static str = "garden.goals.completion";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = CompletionGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Completion<'_> {
    const NSID: &'static str = "garden.goals.completion";
    type Record = CompletionRecord;
}

impl Collection for CompletionRecord {
    const NSID: &'static str = "garden.goals.completion";
    type Record = CompletionRecord;
}

impl<'a> LexiconSchema for Completion<'a> {
    fn nsid() -> &'static str {
        "garden.goals.completion"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_garden_goals_completion()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.day;
            if *value > 31i64 {
                return Err(ConstraintError::Maximum {
                    path: ValidationPath::from_field("day"),
                    max: 31i64,
                    actual: *value,
                });
            }
        }
        {
            let value = &self.day;
            if *value < 1i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("day"),
                    min: 1i64,
                    actual: *value,
                });
            }
        }
        {
            let value = &self.goal_id;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 64usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("goal_id"),
                    max: 64usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.month;
            if *value > 12i64 {
                return Err(ConstraintError::Maximum {
                    path: ValidationPath::from_field("month"),
                    max: 12i64,
                    actual: *value,
                });
            }
        }
        {
            let value = &self.month;
            if *value < 1i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("month"),
                    min: 1i64,
                    actual: *value,
                });
            }
        }
        if let Some(ref value) = self.notes {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 99usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("notes"),
                    max: 99usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.photo_blob {
            {
                let size = value.blob().size;
                if size > 1000000usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("photo_blob"),
                        max: 1000000usize,
                        actual: size,
                    });
                }
            }
        }
        if let Some(ref value) = self.photo_blob {
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &["image/*"];
                let matched = accepted
                    .iter()
                    .any(|pattern| {
                        if *pattern == "*/*" {
                            true
                        } else if pattern.ends_with("/*") {
                            let prefix = &pattern[..pattern.len() - 2];
                            mime.starts_with(prefix)
                                && mime.as_bytes().get(prefix.len()) == Some(&b'/')
                        } else {
                            mime == *pattern
                        }
                    });
                if !matched {
                    return Err(ConstraintError::BlobMimeTypeNotAccepted {
                        path: ValidationPath::from_field("photo_blob"),
                        accepted: vec!["image/*".to_string()],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        if let Some(ref value) = self.sequence_num {
            if *value < 1i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("sequence_num"),
                    min: 1i64,
                    actual: *value,
                });
            }
        }
        {
            let value = &self.year;
            if *value < 1970i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("year"),
                    min: 1970i64,
                    actual: *value,
                });
            }
        }
        Ok(())
    }
}

pub mod completion_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 GoalId;
        type Month;
        type Day;
        type Year;
        type CompletedAt;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type GoalId = Unset;
        type Month = Unset;
        type Day = Unset;
        type Year = Unset;
        type CompletedAt = Unset;
    }
    ///State transition - sets the `goal_id` field to Set
    pub struct SetGoalId<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetGoalId<S> {}
    impl<S: State> State for SetGoalId<S> {
        type GoalId = Set<members::goal_id>;
        type Month = S::Month;
        type Day = S::Day;
        type Year = S::Year;
        type CompletedAt = S::CompletedAt;
    }
    ///State transition - sets the `month` field to Set
    pub struct SetMonth<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetMonth<S> {}
    impl<S: State> State for SetMonth<S> {
        type GoalId = S::GoalId;
        type Month = Set<members::month>;
        type Day = S::Day;
        type Year = S::Year;
        type CompletedAt = S::CompletedAt;
    }
    ///State transition - sets the `day` field to Set
    pub struct SetDay<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetDay<S> {}
    impl<S: State> State for SetDay<S> {
        type GoalId = S::GoalId;
        type Month = S::Month;
        type Day = Set<members::day>;
        type Year = S::Year;
        type CompletedAt = S::CompletedAt;
    }
    ///State transition - sets the `year` field to Set
    pub struct SetYear<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetYear<S> {}
    impl<S: State> State for SetYear<S> {
        type GoalId = S::GoalId;
        type Month = S::Month;
        type Day = S::Day;
        type Year = Set<members::year>;
        type CompletedAt = S::CompletedAt;
    }
    ///State transition - sets the `completed_at` field to Set
    pub struct SetCompletedAt<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetCompletedAt<S> {}
    impl<S: State> State for SetCompletedAt<S> {
        type GoalId = S::GoalId;
        type Month = S::Month;
        type Day = S::Day;
        type Year = S::Year;
        type CompletedAt = Set<members::completed_at>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `goal_id` field
        pub struct goal_id(());
        ///Marker type for the `month` field
        pub struct month(());
        ///Marker type for the `day` field
        pub struct day(());
        ///Marker type for the `year` field
        pub struct year(());
        ///Marker type for the `completed_at` field
        pub struct completed_at(());
    }
}

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

impl<'a> Completion<'a> {
    /// Create a new builder for this type
    pub fn new() -> CompletionBuilder<'a, completion_state::Empty> {
        CompletionBuilder::new()
    }
}

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

impl<'a, S> CompletionBuilder<'a, S>
where
    S: completion_state::State,
    S::CompletedAt: completion_state::IsUnset,
{
    /// Set the `completedAt` field (required)
    pub fn completed_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> CompletionBuilder<'a, completion_state::SetCompletedAt<S>> {
        self._fields.0 = Option::Some(value.into());
        CompletionBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> CompletionBuilder<'a, S>
where
    S: completion_state::State,
    S::Day: completion_state::IsUnset,
{
    /// Set the `day` field (required)
    pub fn day(
        mut self,
        value: impl Into<i64>,
    ) -> CompletionBuilder<'a, completion_state::SetDay<S>> {
        self._fields.1 = Option::Some(value.into());
        CompletionBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> CompletionBuilder<'a, S>
where
    S: completion_state::State,
    S::GoalId: completion_state::IsUnset,
{
    /// Set the `goalId` field (required)
    pub fn goal_id(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> CompletionBuilder<'a, completion_state::SetGoalId<S>> {
        self._fields.2 = Option::Some(value.into());
        CompletionBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: completion_state::State> CompletionBuilder<'a, S> {
    /// Set the `goalUri` field (optional)
    pub fn goal_uri(mut self, value: impl Into<Option<AtUri<'a>>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `goalUri` field to an Option value (optional)
    pub fn maybe_goal_uri(mut self, value: Option<AtUri<'a>>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<'a, S> CompletionBuilder<'a, S>
where
    S: completion_state::State,
    S::Month: completion_state::IsUnset,
{
    /// Set the `month` field (required)
    pub fn month(
        mut self,
        value: impl Into<i64>,
    ) -> CompletionBuilder<'a, completion_state::SetMonth<S>> {
        self._fields.4 = Option::Some(value.into());
        CompletionBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: completion_state::State> CompletionBuilder<'a, S> {
    /// Set the `notes` field (optional)
    pub fn notes(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `notes` field to an Option value (optional)
    pub fn maybe_notes(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<'a, S: completion_state::State> CompletionBuilder<'a, S> {
    /// Set the `photoBlob` field (optional)
    pub fn photo_blob(mut self, value: impl Into<Option<BlobRef<'a>>>) -> Self {
        self._fields.6 = value.into();
        self
    }
    /// Set the `photoBlob` field to an Option value (optional)
    pub fn maybe_photo_blob(mut self, value: Option<BlobRef<'a>>) -> Self {
        self._fields.6 = value;
        self
    }
}

impl<'a, S: completion_state::State> CompletionBuilder<'a, S> {
    /// Set the `sequenceNum` field (optional)
    pub fn sequence_num(mut self, value: impl Into<Option<i64>>) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `sequenceNum` field to an Option value (optional)
    pub fn maybe_sequence_num(mut self, value: Option<i64>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<'a, S> CompletionBuilder<'a, S>
where
    S: completion_state::State,
    S::Year: completion_state::IsUnset,
{
    /// Set the `year` field (required)
    pub fn year(
        mut self,
        value: impl Into<i64>,
    ) -> CompletionBuilder<'a, completion_state::SetYear<S>> {
        self._fields.8 = Option::Some(value.into());
        CompletionBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> CompletionBuilder<'a, S>
where
    S: completion_state::State,
    S::GoalId: completion_state::IsSet,
    S::Month: completion_state::IsSet,
    S::Day: completion_state::IsSet,
    S::Year: completion_state::IsSet,
    S::CompletedAt: completion_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Completion<'a> {
        Completion {
            completed_at: self._fields.0.unwrap(),
            day: self._fields.1.unwrap(),
            goal_id: self._fields.2.unwrap(),
            goal_uri: self._fields.3,
            month: self._fields.4.unwrap(),
            notes: self._fields.5,
            photo_blob: self._fields.6,
            sequence_num: self._fields.7,
            year: self._fields.8.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>,
        >,
    ) -> Completion<'a> {
        Completion {
            completed_at: self._fields.0.unwrap(),
            day: self._fields.1.unwrap(),
            goal_id: self._fields.2.unwrap(),
            goal_uri: self._fields.3,
            month: self._fields.4.unwrap(),
            notes: self._fields.5,
            photo_blob: self._fields.6,
            sequence_num: self._fields.7,
            year: self._fields.8.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_garden_goals_completion() -> 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("garden.goals.completion"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A record of completing a goal on a specific day.",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("goalId"), SmolStr::new_static("year"),
                                SmolStr::new_static("month"), SmolStr::new_static("day"),
                                SmolStr::new_static("completedAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("completedAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Timestamp when the completion was recorded",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("day"),
                                LexObjectProperty::Integer(LexInteger {
                                    minimum: Some(1i64),
                                    maximum: Some(31i64),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("goalId"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "UUID of the goal this completion belongs to",
                                        ),
                                    ),
                                    max_length: Some(64usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("goalUri"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "AT Protocol URI reference to the goal record",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::AtUri),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("month"),
                                LexObjectProperty::Integer(LexInteger {
                                    minimum: Some(1i64),
                                    maximum: Some(12i64),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("notes"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Optional notes for this completion"),
                                    ),
                                    max_length: Some(99usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("photoBlob"),
                                LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                            );
                            map.insert(
                                SmolStr::new_static("sequenceNum"),
                                LexObjectProperty::Integer(LexInteger {
                                    minimum: Some(1i64),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("year"),
                                LexObjectProperty::Integer(LexInteger {
                                    minimum: Some(1970i64),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}