// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: io.atcr.hold.layer
//
// 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::{Did, 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};
/// Represents metadata about a container layer stored in the hold. Stored in the hold's embedded PDS for tracking and analytics.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Layer<'a> {
    ///RFC3339 timestamp of when the layer was uploaded
    pub created_at: Datetime,
    ///Layer digest (e.g., sha256:abc123...)
    #[serde(borrow)]
    pub digest: CowStr<'a>,
    ///AT-URI of the manifest that included this layer (e.g., at://did:plc:xyz/io.atcr.manifest/abc123)
    #[serde(borrow)]
    pub manifest: AtUri<'a>,
    ///Media type (e.g., application/vnd.oci.image.layer.v1.tar+gzip)
    #[serde(borrow)]
    pub media_type: CowStr<'a>,
    ///Size in bytes
    pub size: i64,
    ///DID of user who uploaded this layer
    #[serde(borrow)]
    pub user_did: Did<'a>,
}

/// 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 LayerGetRecordOutput<'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: Layer<'a>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct LayerRecord;
impl XrpcResp for LayerRecord {
    const NSID: &'static str = "io.atcr.hold.layer";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = LayerGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Layer<'_> {
    const NSID: &'static str = "io.atcr.hold.layer";
    type Record = LayerRecord;
}

impl Collection for LayerRecord {
    const NSID: &'static str = "io.atcr.hold.layer";
    type Record = LayerRecord;
}

impl<'a> LexiconSchema for Layer<'a> {
    fn nsid() -> &'static str {
        "io.atcr.hold.layer"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_io_atcr_hold_layer()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.digest;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 128usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("digest"),
                    max: 128usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.media_type;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 128usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("media_type"),
                    max: 128usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod layer_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 Digest;
        type Size;
        type UserDid;
        type CreatedAt;
        type MediaType;
        type Manifest;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Digest = Unset;
        type Size = Unset;
        type UserDid = Unset;
        type CreatedAt = Unset;
        type MediaType = Unset;
        type Manifest = Unset;
    }
    ///State transition - sets the `digest` field to Set
    pub struct SetDigest<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetDigest<S> {}
    impl<S: State> State for SetDigest<S> {
        type Digest = Set<members::digest>;
        type Size = S::Size;
        type UserDid = S::UserDid;
        type CreatedAt = S::CreatedAt;
        type MediaType = S::MediaType;
        type Manifest = S::Manifest;
    }
    ///State transition - sets the `size` field to Set
    pub struct SetSize<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetSize<S> {}
    impl<S: State> State for SetSize<S> {
        type Digest = S::Digest;
        type Size = Set<members::size>;
        type UserDid = S::UserDid;
        type CreatedAt = S::CreatedAt;
        type MediaType = S::MediaType;
        type Manifest = S::Manifest;
    }
    ///State transition - sets the `user_did` field to Set
    pub struct SetUserDid<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetUserDid<S> {}
    impl<S: State> State for SetUserDid<S> {
        type Digest = S::Digest;
        type Size = S::Size;
        type UserDid = Set<members::user_did>;
        type CreatedAt = S::CreatedAt;
        type MediaType = S::MediaType;
        type Manifest = S::Manifest;
    }
    ///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 Digest = S::Digest;
        type Size = S::Size;
        type UserDid = S::UserDid;
        type CreatedAt = Set<members::created_at>;
        type MediaType = S::MediaType;
        type Manifest = S::Manifest;
    }
    ///State transition - sets the `media_type` field to Set
    pub struct SetMediaType<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetMediaType<S> {}
    impl<S: State> State for SetMediaType<S> {
        type Digest = S::Digest;
        type Size = S::Size;
        type UserDid = S::UserDid;
        type CreatedAt = S::CreatedAt;
        type MediaType = Set<members::media_type>;
        type Manifest = S::Manifest;
    }
    ///State transition - sets the `manifest` field to Set
    pub struct SetManifest<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetManifest<S> {}
    impl<S: State> State for SetManifest<S> {
        type Digest = S::Digest;
        type Size = S::Size;
        type UserDid = S::UserDid;
        type CreatedAt = S::CreatedAt;
        type MediaType = S::MediaType;
        type Manifest = Set<members::manifest>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `digest` field
        pub struct digest(());
        ///Marker type for the `size` field
        pub struct size(());
        ///Marker type for the `user_did` field
        pub struct user_did(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `media_type` field
        pub struct media_type(());
        ///Marker type for the `manifest` field
        pub struct manifest(());
    }
}

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

impl<'a> Layer<'a> {
    /// Create a new builder for this type
    pub fn new() -> LayerBuilder<'a, layer_state::Empty> {
        LayerBuilder::new()
    }
}

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

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

impl<'a, S> LayerBuilder<'a, S>
where
    S: layer_state::State,
    S::Digest: layer_state::IsUnset,
{
    /// Set the `digest` field (required)
    pub fn digest(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> LayerBuilder<'a, layer_state::SetDigest<S>> {
        self._fields.1 = Option::Some(value.into());
        LayerBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> LayerBuilder<'a, S>
where
    S: layer_state::State,
    S::Manifest: layer_state::IsUnset,
{
    /// Set the `manifest` field (required)
    pub fn manifest(
        mut self,
        value: impl Into<AtUri<'a>>,
    ) -> LayerBuilder<'a, layer_state::SetManifest<S>> {
        self._fields.2 = Option::Some(value.into());
        LayerBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> LayerBuilder<'a, S>
where
    S: layer_state::State,
    S::MediaType: layer_state::IsUnset,
{
    /// Set the `mediaType` field (required)
    pub fn media_type(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> LayerBuilder<'a, layer_state::SetMediaType<S>> {
        self._fields.3 = Option::Some(value.into());
        LayerBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

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

impl<'a, S> LayerBuilder<'a, S>
where
    S: layer_state::State,
    S::UserDid: layer_state::IsUnset,
{
    /// Set the `userDid` field (required)
    pub fn user_did(
        mut self,
        value: impl Into<Did<'a>>,
    ) -> LayerBuilder<'a, layer_state::SetUserDid<S>> {
        self._fields.5 = Option::Some(value.into());
        LayerBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> LayerBuilder<'a, S>
where
    S: layer_state::State,
    S::Digest: layer_state::IsSet,
    S::Size: layer_state::IsSet,
    S::UserDid: layer_state::IsSet,
    S::CreatedAt: layer_state::IsSet,
    S::MediaType: layer_state::IsSet,
    S::Manifest: layer_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Layer<'a> {
        Layer {
            created_at: self._fields.0.unwrap(),
            digest: self._fields.1.unwrap(),
            manifest: self._fields.2.unwrap(),
            media_type: self._fields.3.unwrap(),
            size: self._fields.4.unwrap(),
            user_did: 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>,
        >,
    ) -> Layer<'a> {
        Layer {
            created_at: self._fields.0.unwrap(),
            digest: self._fields.1.unwrap(),
            manifest: self._fields.2.unwrap(),
            media_type: self._fields.3.unwrap(),
            size: self._fields.4.unwrap(),
            user_did: self._fields.5.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_io_atcr_hold_layer() -> 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("io.atcr.hold.layer"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "Represents metadata about a container layer stored in the hold. Stored in the hold's embedded PDS for tracking and analytics.",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("digest"), SmolStr::new_static("size"),
                                SmolStr::new_static("mediaType"),
                                SmolStr::new_static("manifest"),
                                SmolStr::new_static("userDid"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "RFC3339 timestamp of when the layer was uploaded",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("digest"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Layer digest (e.g., sha256:abc123...)"),
                                    ),
                                    max_length: Some(128usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("manifest"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "AT-URI of the manifest that included this layer (e.g., at://did:plc:xyz/io.atcr.manifest/abc123)",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::AtUri),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("mediaType"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Media type (e.g., application/vnd.oci.image.layer.v1.tar+gzip)",
                                        ),
                                    ),
                                    max_length: Some(128usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("size"),
                                LexObjectProperty::Integer(LexInteger {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("userDid"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("DID of user who uploaded this layer"),
                                    ),
                                    format: Some(LexStringFormat::Did),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}