// @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, 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::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::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 record of completing a goal on a specific day.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "garden.goals.completion",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Completion<S: BosStr = DefaultStr> {
    ///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
    pub goal_id: S,
    ///AT Protocol URI reference to the goal record
    #[serde(skip_serializing_if = "Option::is_none")]
    pub goal_uri: Option<AtUri<S>>,
    ///Month of the completion (1-12)
    pub month: i64,
    ///Optional notes for this completion
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notes: Option<S>,
    ///Optional photo for this completion
    #[serde(skip_serializing_if = "Option::is_none")]
    pub photo_blob: Option<BlobRef<S>>,
    ///Sequence number for countable goals
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sequence_num: Option<i64>,
    ///Year of the completion
    pub year: i64,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// 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<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Completion<S>,
}

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

/// 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<S: BosStr> = CompletionGetRecordOutput<S>;
    type Err = RecordError;
}

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

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

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

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

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

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

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

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

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

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

impl<St: completion_state::State, S: BosStr> CompletionBuilder<St, S> {
    /// Set the `goalUri` field (optional)
    pub fn goal_uri(mut self, value: impl Into<Option<AtUri<S>>>) -> 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<S>>) -> Self {
        self._fields.3 = value;
        self
    }
}

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

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

impl<St: completion_state::State, S: BosStr> CompletionBuilder<St, S> {
    /// Set the `photoBlob` field (optional)
    pub fn photo_blob(mut self, value: impl Into<Option<BlobRef<S>>>) -> 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<S>>) -> Self {
        self._fields.6 = value;
        self
    }
}

impl<St: completion_state::State, S: BosStr> CompletionBuilder<St, 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<St, S: BosStr> CompletionBuilder<St, S>
where
    St: completion_state::State,
    St::Year: completion_state::IsUnset,
{
    /// Set the `year` field (required)
    pub fn year(
        mut self,
        value: impl Into<i64>,
    ) -> CompletionBuilder<completion_state::SetYear<St>, S> {
        self._fields.8 = Option::Some(value.into());
        CompletionBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> CompletionBuilder<St, S>
where
    St: completion_state::State,
    St::CompletedAt: completion_state::IsSet,
    St::Day: completion_state::IsSet,
    St::GoalId: completion_state::IsSet,
    St::Month: completion_state::IsSet,
    St::Year: completion_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Completion<S> {
        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<SmolStr, Data<S>>,
    ) -> Completion<S> {
        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()
    }
}