// @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, 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::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::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};
/// A simple record referencing a file hosted on a PDS

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "sh.weaver.publish.blob",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Blob<S: BosStr = DefaultStr> {
    ///relative path to the blob
    pub path: S,
    ///Reference to the uploaded file
    pub upload: BlobRef<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 BlobGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Blob<S>,
}

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

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

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

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

/// Builder for constructing an instance of this type.
pub struct BlobBuilder<St: blob_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (Option<S>, Option<BlobRef<S>>),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

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

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

impl<St, S: BosStr> BlobBuilder<St, S>
where
    St: blob_state::State,
    St::Path: blob_state::IsSet,
    St::Upload: blob_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Blob<S> {
        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<SmolStr, Data<S>>) -> Blob<S> {
        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()
    }
}