// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: garden.goals.completionDetails
//
// 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};
/// Additional details (notes, photo) for a goal completion day.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct CompletionDetails<'a> {
    ///Day of the completion (1-31)
    pub day: i64,
    ///UUID of the goal this details record 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 day
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub notes: Option<CowStr<'a>>,
    ///Alt text for the photo
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub photo_alt: Option<CowStr<'a>>,
    ///Optional photo for this day
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub photo_blob: Option<BlobRef<'a>>,
    ///Timestamp when this details record was last updated
    pub updated_at: Datetime,
    ///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 CompletionDetailsGetRecordOutput<'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: CompletionDetails<'a>,
}

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

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

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

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

impl Collection for CompletionDetails<'_> {
    const NSID: &'static str = "garden.goals.completionDetails";
    type Record = CompletionDetailsRecord;
}

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

impl<'a> LexiconSchema for CompletionDetails<'a> {
    fn nsid() -> &'static str {
        "garden.goals.completionDetails"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_garden_goals_completionDetails()
    }
    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_alt {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 1000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("photo_alt"),
                    max: 1000usize,
                    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(),
                    });
                }
            }
        }
        {
            let value = &self.year;
            if *value < 1970i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("year"),
                    min: 1970i64,
                    actual: *value,
                });
            }
        }
        Ok(())
    }
}

pub mod completion_details_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 Day;
        type GoalId;
        type UpdatedAt;
        type Month;
        type Year;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Day = Unset;
        type GoalId = Unset;
        type UpdatedAt = Unset;
        type Month = Unset;
        type Year = Unset;
    }
    ///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 Day = Set<members::day>;
        type GoalId = S::GoalId;
        type UpdatedAt = S::UpdatedAt;
        type Month = S::Month;
        type Year = S::Year;
    }
    ///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 Day = S::Day;
        type GoalId = Set<members::goal_id>;
        type UpdatedAt = S::UpdatedAt;
        type Month = S::Month;
        type Year = S::Year;
    }
    ///State transition - sets the `updated_at` field to Set
    pub struct SetUpdatedAt<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetUpdatedAt<S> {}
    impl<S: State> State for SetUpdatedAt<S> {
        type Day = S::Day;
        type GoalId = S::GoalId;
        type UpdatedAt = Set<members::updated_at>;
        type Month = S::Month;
        type Year = S::Year;
    }
    ///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 Day = S::Day;
        type GoalId = S::GoalId;
        type UpdatedAt = S::UpdatedAt;
        type Month = Set<members::month>;
        type Year = S::Year;
    }
    ///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 Day = S::Day;
        type GoalId = S::GoalId;
        type UpdatedAt = S::UpdatedAt;
        type Month = S::Month;
        type Year = Set<members::year>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `day` field
        pub struct day(());
        ///Marker type for the `goal_id` field
        pub struct goal_id(());
        ///Marker type for the `updated_at` field
        pub struct updated_at(());
        ///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 CompletionDetailsBuilder<'a, S: completion_details_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<i64>,
        Option<CowStr<'a>>,
        Option<AtUri<'a>>,
        Option<i64>,
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
        Option<BlobRef<'a>>,
        Option<Datetime>,
        Option<i64>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> CompletionDetails<'a> {
    /// Create a new builder for this type
    pub fn new() -> CompletionDetailsBuilder<'a, completion_details_state::Empty> {
        CompletionDetailsBuilder::new()
    }
}

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

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

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

impl<'a, S: completion_details_state::State> CompletionDetailsBuilder<'a, S> {
    /// Set the `goalUri` field (optional)
    pub fn goal_uri(mut self, value: impl Into<Option<AtUri<'a>>>) -> Self {
        self._fields.2 = 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.2 = value;
        self
    }
}

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

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

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

impl<'a, S: completion_details_state::State> CompletionDetailsBuilder<'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> CompletionDetailsBuilder<'a, S>
where
    S: completion_details_state::State,
    S::UpdatedAt: completion_details_state::IsUnset,
{
    /// Set the `updatedAt` field (required)
    pub fn updated_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> CompletionDetailsBuilder<'a, completion_details_state::SetUpdatedAt<S>> {
        self._fields.7 = Option::Some(value.into());
        CompletionDetailsBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

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

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

fn lexicon_doc_garden_goals_completionDetails() -> 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.completionDetails"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "Additional details (notes, photo) for a goal completion 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("updatedAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            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 details record 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 day"),
                                    ),
                                    max_length: Some(99usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("photoAlt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Alt text for the photo"),
                                    ),
                                    max_length: Some(1000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("photoBlob"),
                                LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                            );
                            map.insert(
                                SmolStr::new_static("updatedAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Timestamp when this details record was last updated",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("year"),
                                LexObjectProperty::Integer(LexInteger {
                                    minimum: Some(1970i64),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}