// @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, 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::collection::{Collection, RecordError};
use jacquard_common::types::string::{Did, 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};
/// Represents metadata about a container layer stored in the hold. Stored in the hold's embedded PDS for tracking and analytics.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "io.atcr.hold.layer",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Layer<S: BosStr = DefaultStr> {
    ///RFC3339 timestamp of when the layer was uploaded
    pub created_at: Datetime,
    ///Layer digest (e.g., sha256:abc123...)
    pub digest: S,
    ///AT-URI of the manifest that included this layer (e.g., at://did:plc:xyz/io.atcr.manifest/abc123)
    pub manifest: AtUri<S>,
    ///Media type (e.g., application/vnd.oci.image.layer.v1.tar+gzip)
    pub media_type: S,
    ///Size in bytes
    pub size: i64,
    ///DID of user who uploaded this layer
    pub user_did: Did<S>,
    #[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 LayerGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Layer<S>,
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

impl<St, S: BosStr> LayerBuilder<St, S>
where
    St: layer_state::State,
    St::CreatedAt: layer_state::IsSet,
    St::Digest: layer_state::IsSet,
    St::Manifest: layer_state::IsSet,
    St::MediaType: layer_state::IsSet,
    St::Size: layer_state::IsSet,
    St::UserDid: layer_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Layer<S> {
        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<SmolStr, Data<S>>) -> Layer<S> {
        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()
    }
}