// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: tech.lenooby09.didgit.object
//
// 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};
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 did-git object stored in an AT Protocol repository. Each record represents a single content-addressable object (blob, tree, commit, or tag), keyed by its hex SHA-256 object ID.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Object<'a> {
    ///The git object content, stored as an AT Protocol blob.
    #[serde(borrow)]
    pub content: BlobRef<'a>,
    ///The type of the git object.
    #[serde(borrow)]
    pub object_type: ObjectObjectType<'a>,
}

/// The type of the git object.

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ObjectObjectType<'a> {
    Blob,
    Tree,
    Commit,
    Tag,
    Other(CowStr<'a>),
}

impl<'a> ObjectObjectType<'a> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Blob => "blob",
            Self::Tree => "tree",
            Self::Commit => "commit",
            Self::Tag => "tag",
            Self::Other(s) => s.as_ref(),
        }
    }
}

impl<'a> From<&'a str> for ObjectObjectType<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "blob" => Self::Blob,
            "tree" => Self::Tree,
            "commit" => Self::Commit,
            "tag" => Self::Tag,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for ObjectObjectType<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "blob" => Self::Blob,
            "tree" => Self::Tree,
            "commit" => Self::Commit,
            "tag" => Self::Tag,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

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

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

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

impl jacquard_common::IntoStatic for ObjectObjectType<'_> {
    type Output = ObjectObjectType<'static>;
    fn into_static(self) -> Self::Output {
        match self {
            ObjectObjectType::Blob => ObjectObjectType::Blob,
            ObjectObjectType::Tree => ObjectObjectType::Tree,
            ObjectObjectType::Commit => ObjectObjectType::Commit,
            ObjectObjectType::Tag => ObjectObjectType::Tag,
            ObjectObjectType::Other(v) => ObjectObjectType::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 ObjectGetRecordOutput<'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: Object<'a>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct ObjectRecord;
impl XrpcResp for ObjectRecord {
    const NSID: &'static str = "tech.lenooby09.didgit.object";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = ObjectGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Object<'_> {
    const NSID: &'static str = "tech.lenooby09.didgit.object";
    type Record = ObjectRecord;
}

impl Collection for ObjectRecord {
    const NSID: &'static str = "tech.lenooby09.didgit.object";
    type Record = ObjectRecord;
}

impl<'a> LexiconSchema for Object<'a> {
    fn nsid() -> &'static str {
        "tech.lenooby09.didgit.object"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_tech_lenooby09_didgit_object()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.content;
            {
                let size = value.blob().size;
                if size > 52428800usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("content"),
                        max: 52428800usize,
                        actual: size,
                    });
                }
            }
        }
        {
            let value = &self.content;
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &["application/octet-stream"];
                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("content"),
                        accepted: vec!["application/octet-stream".to_string()],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        {
            let value = &self.object_type;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 16usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("object_type"),
                    max: 16usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod object_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 Content;
        type ObjectType;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Content = Unset;
        type ObjectType = Unset;
    }
    ///State transition - sets the `content` field to Set
    pub struct SetContent<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetContent<S> {}
    impl<S: State> State for SetContent<S> {
        type Content = Set<members::content>;
        type ObjectType = S::ObjectType;
    }
    ///State transition - sets the `object_type` field to Set
    pub struct SetObjectType<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetObjectType<S> {}
    impl<S: State> State for SetObjectType<S> {
        type Content = S::Content;
        type ObjectType = Set<members::object_type>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `content` field
        pub struct content(());
        ///Marker type for the `object_type` field
        pub struct object_type(());
    }
}

/// Builder for constructing an instance of this type
pub struct ObjectBuilder<'a, S: object_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (Option<BlobRef<'a>>, Option<ObjectObjectType<'a>>),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Object<'a> {
    /// Create a new builder for this type
    pub fn new() -> ObjectBuilder<'a, object_state::Empty> {
        ObjectBuilder::new()
    }
}

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

impl<'a, S> ObjectBuilder<'a, S>
where
    S: object_state::State,
    S::Content: object_state::IsUnset,
{
    /// Set the `content` field (required)
    pub fn content(
        mut self,
        value: impl Into<BlobRef<'a>>,
    ) -> ObjectBuilder<'a, object_state::SetContent<S>> {
        self._fields.0 = Option::Some(value.into());
        ObjectBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> ObjectBuilder<'a, S>
where
    S: object_state::State,
    S::ObjectType: object_state::IsUnset,
{
    /// Set the `objectType` field (required)
    pub fn object_type(
        mut self,
        value: impl Into<ObjectObjectType<'a>>,
    ) -> ObjectBuilder<'a, object_state::SetObjectType<S>> {
        self._fields.1 = Option::Some(value.into());
        ObjectBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> ObjectBuilder<'a, S>
where
    S: object_state::State,
    S::Content: object_state::IsSet,
    S::ObjectType: object_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Object<'a> {
        Object {
            content: self._fields.0.unwrap(),
            object_type: self._fields.1.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>,
        >,
    ) -> Object<'a> {
        Object {
            content: self._fields.0.unwrap(),
            object_type: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_tech_lenooby09_didgit_object() -> 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("tech.lenooby09.didgit.object"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A did-git object stored in an AT Protocol repository. Each record represents a single content-addressable object (blob, tree, commit, or tag), keyed by its hex SHA-256 object ID.",
                        ),
                    ),
                    key: Some(CowStr::new_static("any")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("objectType"),
                                SmolStr::new_static("content")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("content"),
                                LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                            );
                            map.insert(
                                SmolStr::new_static("objectType"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("The type of the git object."),
                                    ),
                                    max_length: Some(16usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}