// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: net.altq.aqfile
//
// 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::ident::AtIdentifier;
use jacquard_common::types::string::{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};
use crate::net_altq::aqfile;
/// Cryptographic checksum for integrity verification.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Checksum<S: BosStr = DefaultStr> {
    ///Hash algorithm name.
    pub algo: ChecksumAlgo<S>,
    ///Hex or base64 encoded digest produced by the algorithm.
    pub hash: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// Hash algorithm name.

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ChecksumAlgo<S: BosStr = DefaultStr> {
    Sha256,
    Sha512,
    Blake3,
    Other(S),
}

impl<S: BosStr> ChecksumAlgo<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Sha256 => "sha256",
            Self::Sha512 => "sha512",
            Self::Blake3 => "blake3",
            Self::Other(s) => s.as_ref(),
        }
    }
    /// Construct from a string-like value, matching known values.
    pub fn from_value(s: S) -> Self {
        match s.as_ref() {
            "sha256" => Self::Sha256,
            "sha512" => Self::Sha512,
            "blake3" => Self::Blake3,
            _ => Self::Other(s),
        }
    }
}

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

impl<S: BosStr> AsRef<str> for ChecksumAlgo<S> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<S: BosStr> Serialize for ChecksumAlgo<S> {
    fn serialize<Ser>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
    where
        Ser: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de, S: Deserialize<'de> + BosStr> Deserialize<'de> for ChecksumAlgo<S> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = S::deserialize(deserializer)?;
        Ok(Self::from_value(s))
    }
}

impl<S: BosStr + Default> Default for ChecksumAlgo<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for ChecksumAlgo<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = ChecksumAlgo<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            ChecksumAlgo::Sha256 => ChecksumAlgo::Sha256,
            ChecksumAlgo::Sha512 => ChecksumAlgo::Sha512,
            ChecksumAlgo::Blake3 => ChecksumAlgo::Blake3,
            ChecksumAlgo::Other(v) => ChecksumAlgo::Other(v.into_static()),
        }
    }
}

/// File metadata describing the uploaded blob.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct File<S: BosStr = DefaultStr> {
    ///MIME type, e.g. 'video/mp4'.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mime_type: Option<S>,
    ///Client-side last-modified timestamp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub modified_at: Option<Datetime>,
    ///User-visible filename.
    pub name: S,
    ///File size in bytes.
    pub size: i64,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// A record representing an uploaded file blob with metadata.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "net.altq.aqfile",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Aqfile<S: BosStr = DefaultStr> {
    ///Handle or DID of the account to attribute this upload to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attribution: Option<AtIdentifier<S>>,
    ///The uploaded blob reference. Note: Individual PDS instances may enforce lower size limits.
    pub blob: BlobRef<S>,
    ///Optional cryptographic checksum for integrity verification.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub checksum: Option<aqfile::Checksum<S>>,
    ///Timestamp when this record was created.
    pub created_at: Datetime,
    ///Metadata about the file.
    pub file: aqfile::File<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 AqfileGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Aqfile<S>,
}

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

impl<S: BosStr> LexiconSchema for Checksum<S> {
    fn nsid() -> &'static str {
        "net.altq.aqfile"
    }
    fn def_name() -> &'static str {
        "checksum"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_net_altq_aqfile()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.algo;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 32usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("algo"),
                    max: 32usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.hash;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 128usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("hash"),
                    max: 128usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for File<S> {
    fn nsid() -> &'static str {
        "net.altq.aqfile"
    }
    fn def_name() -> &'static str {
        "file"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_net_altq_aqfile()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.mime_type {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 255usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("mime_type"),
                    max: 255usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.name;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 512usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("name"),
                    max: 512usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.size;
            if *value > 1000000000i64 {
                return Err(ConstraintError::Maximum {
                    path: ValidationPath::from_field("size"),
                    max: 1000000000i64,
                    actual: *value,
                });
            }
        }
        {
            let value = &self.size;
            if *value < 0i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("size"),
                    min: 0i64,
                    actual: *value,
                });
            }
        }
        Ok(())
    }
}

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

#[derive(Debug, Serialize, Deserialize)]
pub struct AqfileRecord;
impl XrpcResp for AqfileRecord {
    const NSID: &'static str = "net.altq.aqfile";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = AqfileGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Aqfile<S> {
    const NSID: &'static str = "net.altq.aqfile";
    type Record = AqfileRecord;
}

impl Collection for AqfileRecord {
    const NSID: &'static str = "net.altq.aqfile";
    type Record = AqfileRecord;
}

impl<S: BosStr> LexiconSchema for Aqfile<S> {
    fn nsid() -> &'static str {
        "net.altq.aqfile"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_net_altq_aqfile()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.blob;
            {
                let size = value.blob().size;
                if size > 1000000000usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("blob"),
                        max: 1000000000usize,
                        actual: size,
                    });
                }
            }
        }
        {
            let value = &self.blob;
            {
                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("blob"),
                        accepted: vec!["*/*".to_string()],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        Ok(())
    }
}

fn lexicon_doc_net_altq_aqfile() -> 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("net.altq.aqfile"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("checksum"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "Cryptographic checksum for integrity verification.",
                        ),
                    ),
                    required: Some(
                        vec![SmolStr::new_static("algo"), SmolStr::new_static("hash")],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("algo"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Hash algorithm name."),
                                ),
                                max_length: Some(32usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("hash"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "Hex or base64 encoded digest produced by the algorithm.",
                                    ),
                                ),
                                max_length: Some(128usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("file"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static("File metadata describing the uploaded blob."),
                    ),
                    required: Some(
                        vec![SmolStr::new_static("name"), SmolStr::new_static("size")],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("mimeType"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("MIME type, e.g. 'video/mp4'."),
                                ),
                                max_length: Some(255usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("modifiedAt"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Client-side last-modified timestamp."),
                                ),
                                format: Some(LexStringFormat::Datetime),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("name"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("User-visible filename."),
                                ),
                                max_length: Some(512usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("size"),
                            LexObjectProperty::Integer(LexInteger {
                                minimum: Some(0i64),
                                maximum: Some(1000000000i64),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A record representing an uploaded file blob with metadata.",
                        ),
                    ),
                    key: Some(CowStr::new_static("any")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("blob"),
                                SmolStr::new_static("createdAt"),
                                SmolStr::new_static("file")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("attribution"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Handle or DID of the account to attribute this upload to.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::AtIdentifier),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("blob"),
                                LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                            );
                            map.insert(
                                SmolStr::new_static("checksum"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("#checksum"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Timestamp when this record was created.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("file"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("#file"),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod file_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 Name;
        type Size;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Name = Unset;
        type Size = Unset;
    }
    ///State transition - sets the `name` field to Set
    pub struct SetName<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetName<St> {}
    impl<St: State> State for SetName<St> {
        type Name = Set<members::name>;
        type Size = St::Size;
    }
    ///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 Name = St::Name;
        type Size = Set<members::size>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `name` field
        pub struct name(());
        ///Marker type for the `size` field
        pub struct size(());
    }
}

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

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

impl<S: BosStr> File<S> {
    /// Create a new builder for this type
    pub fn builder() -> FileBuilder<file_state::Empty, S> {
        FileBuilder::builder()
    }
}

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

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

impl<St: file_state::State, S: BosStr> FileBuilder<St, S> {
    /// Set the `mimeType` field (optional)
    pub fn mime_type(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `mimeType` field to an Option value (optional)
    pub fn maybe_mime_type(mut self, value: Option<S>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St: file_state::State, S: BosStr> FileBuilder<St, S> {
    /// Set the `modifiedAt` field (optional)
    pub fn modified_at(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `modifiedAt` field to an Option value (optional)
    pub fn maybe_modified_at(mut self, value: Option<Datetime>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<St, S: BosStr> FileBuilder<St, S>
where
    St: file_state::State,
    St::Name: file_state::IsUnset,
{
    /// Set the `name` field (required)
    pub fn name(
        mut self,
        value: impl Into<S>,
    ) -> FileBuilder<file_state::SetName<St>, S> {
        self._fields.2 = Option::Some(value.into());
        FileBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

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

impl<St, S: BosStr> FileBuilder<St, S>
where
    St: file_state::State,
    St::Name: file_state::IsSet,
    St::Size: file_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> File<S> {
        File {
            mime_type: self._fields.0,
            modified_at: self._fields.1,
            name: self._fields.2.unwrap(),
            size: self._fields.3.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>>) -> File<S> {
        File {
            mime_type: self._fields.0,
            modified_at: self._fields.1,
            name: self._fields.2.unwrap(),
            size: self._fields.3.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

pub mod aqfile_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 Blob;
        type CreatedAt;
        type File;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Blob = Unset;
        type CreatedAt = Unset;
        type File = Unset;
    }
    ///State transition - sets the `blob` field to Set
    pub struct SetBlob<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetBlob<St> {}
    impl<St: State> State for SetBlob<St> {
        type Blob = Set<members::blob>;
        type CreatedAt = St::CreatedAt;
        type File = St::File;
    }
    ///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 Blob = St::Blob;
        type CreatedAt = Set<members::created_at>;
        type File = St::File;
    }
    ///State transition - sets the `file` field to Set
    pub struct SetFile<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetFile<St> {}
    impl<St: State> State for SetFile<St> {
        type Blob = St::Blob;
        type CreatedAt = St::CreatedAt;
        type File = Set<members::file>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `blob` field
        pub struct blob(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `file` field
        pub struct file(());
    }
}

/// Builder for constructing an instance of this type.
pub struct AqfileBuilder<St: aqfile_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<AtIdentifier<S>>,
        Option<BlobRef<S>>,
        Option<aqfile::Checksum<S>>,
        Option<Datetime>,
        Option<aqfile::File<S>>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> Aqfile<S> {
    /// Create a new builder for this type
    pub fn builder() -> AqfileBuilder<aqfile_state::Empty, S> {
        AqfileBuilder::builder()
    }
}

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

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

impl<St: aqfile_state::State, S: BosStr> AqfileBuilder<St, S> {
    /// Set the `attribution` field (optional)
    pub fn attribution(mut self, value: impl Into<Option<AtIdentifier<S>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `attribution` field to an Option value (optional)
    pub fn maybe_attribution(mut self, value: Option<AtIdentifier<S>>) -> Self {
        self._fields.0 = value;
        self
    }
}

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

impl<St: aqfile_state::State, S: BosStr> AqfileBuilder<St, S> {
    /// Set the `checksum` field (optional)
    pub fn checksum(mut self, value: impl Into<Option<aqfile::Checksum<S>>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `checksum` field to an Option value (optional)
    pub fn maybe_checksum(mut self, value: Option<aqfile::Checksum<S>>) -> Self {
        self._fields.2 = value;
        self
    }
}

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

impl<St, S: BosStr> AqfileBuilder<St, S>
where
    St: aqfile_state::State,
    St::File: aqfile_state::IsUnset,
{
    /// Set the `file` field (required)
    pub fn file(
        mut self,
        value: impl Into<aqfile::File<S>>,
    ) -> AqfileBuilder<aqfile_state::SetFile<St>, S> {
        self._fields.4 = Option::Some(value.into());
        AqfileBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> AqfileBuilder<St, S>
where
    St: aqfile_state::State,
    St::Blob: aqfile_state::IsSet,
    St::CreatedAt: aqfile_state::IsSet,
    St::File: aqfile_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Aqfile<S> {
        Aqfile {
            attribution: self._fields.0,
            blob: self._fields.1.unwrap(),
            checksum: self._fields.2,
            created_at: self._fields.3.unwrap(),
            file: self._fields.4.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>>) -> Aqfile<S> {
        Aqfile {
            attribution: self._fields.0,
            blob: self._fields.1.unwrap(),
            checksum: self._fields.2,
            created_at: self._fields.3.unwrap(),
            file: self._fields.4.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}