// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: sh.weaver.publish.blob
//
// 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 simple record referencing a file hosted on a PDS

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Blob<'a> {
    ///relative path to the blob
    #[serde(borrow)]
    pub path: CowStr<'a>,
    ///Reference to the uploaded file
    #[serde(borrow)]
    pub upload: BlobRef<'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 BlobGetRecordOutput<'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: Blob<'a>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct BlobRecord;
impl XrpcResp for BlobRecord {
    const NSID: &'static str = "sh.weaver.publish.blob";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = BlobGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Blob<'_> {
    const NSID: &'static str = "sh.weaver.publish.blob";
    type Record = BlobRecord;
}

impl Collection for BlobRecord {
    const NSID: &'static str = "sh.weaver.publish.blob";
    type Record = BlobRecord;
}

impl<'a> LexiconSchema for Blob<'a> {
    fn nsid() -> &'static str {
        "sh.weaver.publish.blob"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_sh_weaver_publish_blob()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.path;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) < 1usize {
                return Err(ConstraintError::MinLength {
                    path: ValidationPath::from_field("path"),
                    min: 1usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.upload;
            {
                let size = value.blob().size;
                if size > 10000000usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("upload"),
                        max: 10000000usize,
                        actual: size,
                    });
                }
            }
        }
        {
            let value = &self.upload;
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &["*/*"];
                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("upload"),
                        accepted: vec!["*/*".to_string()],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        Ok(())
    }
}

pub mod blob_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 Upload;
        type Path;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Upload = Unset;
        type Path = Unset;
    }
    ///State transition - sets the `upload` field to Set
    pub struct SetUpload<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetUpload<S> {}
    impl<S: State> State for SetUpload<S> {
        type Upload = Set<members::upload>;
        type Path = S::Path;
    }
    ///State transition - sets the `path` field to Set
    pub struct SetPath<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetPath<S> {}
    impl<S: State> State for SetPath<S> {
        type Upload = S::Upload;
        type Path = Set<members::path>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `upload` field
        pub struct upload(());
        ///Marker type for the `path` field
        pub struct path(());
    }
}

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

impl<'a> Blob<'a> {
    /// Create a new builder for this type
    pub fn new() -> BlobBuilder<'a, blob_state::Empty> {
        BlobBuilder::new()
    }
}

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

impl<'a, S> BlobBuilder<'a, S>
where
    S: blob_state::State,
    S::Path: blob_state::IsUnset,
{
    /// Set the `path` field (required)
    pub fn path(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> BlobBuilder<'a, blob_state::SetPath<S>> {
        self._fields.0 = Option::Some(value.into());
        BlobBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> BlobBuilder<'a, S>
where
    S: blob_state::State,
    S::Upload: blob_state::IsUnset,
{
    /// Set the `upload` field (required)
    pub fn upload(
        mut self,
        value: impl Into<BlobRef<'a>>,
    ) -> BlobBuilder<'a, blob_state::SetUpload<S>> {
        self._fields.1 = Option::Some(value.into());
        BlobBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> BlobBuilder<'a, S>
where
    S: blob_state::State,
    S::Upload: blob_state::IsSet,
    S::Path: blob_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Blob<'a> {
        Blob {
            path: self._fields.0.unwrap(),
            upload: 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>,
        >,
    ) -> Blob<'a> {
        Blob {
            path: self._fields.0.unwrap(),
            upload: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_sh_weaver_publish_blob() -> 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("sh.weaver.publish.blob"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A simple record referencing a file hosted on a PDS",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("upload"), SmolStr::new_static("path")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("path"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("relative path to the blob"),
                                    ),
                                    min_length: Some(1usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("upload"),
                                LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}