// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: net.alternativeproto.submission
//
// 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, Datetime, UriValue};
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 user submission of a project to AlternativeProto

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Submission<'a> {
    ///Services this project is an alternative to
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub alternative_to: Option<Vec<CowStr<'a>>>,
    ///Authentication method used by the project
    #[serde(borrow)]
    pub auth_type: SubmissionAuthType<'a>,
    ///Timestamp when the submission was created
    pub created_at: Datetime,
    ///Description of the project
    #[serde(borrow)]
    pub description: CowStr<'a>,
    ///Project icon image blob
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub icon: Option<BlobRef<'a>>,
    ///Whether the project is open source
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_open_source: Option<bool>,
    ///The project name
    #[serde(borrow)]
    pub name: CowStr<'a>,
    ///Source code repository URL
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub repository_url: Option<UriValue<'a>>,
    ///Tags for categorization
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub tags: Option<Vec<CowStr<'a>>>,
    ///The project URL
    #[serde(borrow)]
    pub url: UriValue<'a>,
}

/// Authentication method used by the project

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SubmissionAuthType<'a> {
    Oauth,
    AppPassword,
    None,
    Other(CowStr<'a>),
}

impl<'a> SubmissionAuthType<'a> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Oauth => "oauth",
            Self::AppPassword => "app-password",
            Self::None => "none",
            Self::Other(s) => s.as_ref(),
        }
    }
}

impl<'a> From<&'a str> for SubmissionAuthType<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "oauth" => Self::Oauth,
            "app-password" => Self::AppPassword,
            "none" => Self::None,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for SubmissionAuthType<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "oauth" => Self::Oauth,
            "app-password" => Self::AppPassword,
            "none" => Self::None,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

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

impl<'a> AsRef<str> for SubmissionAuthType<'a> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

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

impl<'de, 'a> serde::Deserialize<'de> for SubmissionAuthType<'a>
where
    'de: 'a,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = <&'de str>::deserialize(deserializer)?;
        Ok(Self::from(s))
    }
}

impl<'a> Default for SubmissionAuthType<'a> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl jacquard_common::IntoStatic for SubmissionAuthType<'_> {
    type Output = SubmissionAuthType<'static>;
    fn into_static(self) -> Self::Output {
        match self {
            SubmissionAuthType::Oauth => SubmissionAuthType::Oauth,
            SubmissionAuthType::AppPassword => SubmissionAuthType::AppPassword,
            SubmissionAuthType::None => SubmissionAuthType::None,
            SubmissionAuthType::Other(v) => SubmissionAuthType::Other(v.into_static()),
        }
    }
}

/// 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 SubmissionGetRecordOutput<'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: Submission<'a>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct SubmissionRecord;
impl XrpcResp for SubmissionRecord {
    const NSID: &'static str = "net.alternativeproto.submission";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = SubmissionGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Submission<'_> {
    const NSID: &'static str = "net.alternativeproto.submission";
    type Record = SubmissionRecord;
}

impl Collection for SubmissionRecord {
    const NSID: &'static str = "net.alternativeproto.submission";
    type Record = SubmissionRecord;
}

impl<'a> LexiconSchema for Submission<'a> {
    fn nsid() -> &'static str {
        "net.alternativeproto.submission"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_net_alternativeproto_submission()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.description;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 5000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("description"),
                    max: 5000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.icon {
            {
                let size = value.blob().size;
                if size > 1000000usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("icon"),
                        max: 1000000usize,
                        actual: size,
                    });
                }
            }
        }
        if let Some(ref value) = self.icon {
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &[
                    "image/png",
                    "image/jpeg",
                    "image/webp",
                    "image/svg+xml",
                    "image/x-icon",
                    "image/vnd.microsoft.icon",
                ];
                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("icon"),
                        accepted: vec![
                            "image/png".to_string(), "image/jpeg".to_string(),
                            "image/webp".to_string(), "image/svg+xml".to_string(),
                            "image/x-icon".to_string(), "image/vnd.microsoft.icon"
                            .to_string()
                        ],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        {
            let value = &self.name;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 200usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("name"),
                    max: 200usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod submission_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 Url;
        type Description;
        type AuthType;
        type CreatedAt;
        type Name;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Url = Unset;
        type Description = Unset;
        type AuthType = Unset;
        type CreatedAt = Unset;
        type Name = Unset;
    }
    ///State transition - sets the `url` field to Set
    pub struct SetUrl<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetUrl<S> {}
    impl<S: State> State for SetUrl<S> {
        type Url = Set<members::url>;
        type Description = S::Description;
        type AuthType = S::AuthType;
        type CreatedAt = S::CreatedAt;
        type Name = S::Name;
    }
    ///State transition - sets the `description` field to Set
    pub struct SetDescription<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetDescription<S> {}
    impl<S: State> State for SetDescription<S> {
        type Url = S::Url;
        type Description = Set<members::description>;
        type AuthType = S::AuthType;
        type CreatedAt = S::CreatedAt;
        type Name = S::Name;
    }
    ///State transition - sets the `auth_type` field to Set
    pub struct SetAuthType<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetAuthType<S> {}
    impl<S: State> State for SetAuthType<S> {
        type Url = S::Url;
        type Description = S::Description;
        type AuthType = Set<members::auth_type>;
        type CreatedAt = S::CreatedAt;
        type Name = S::Name;
    }
    ///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 Url = S::Url;
        type Description = S::Description;
        type AuthType = S::AuthType;
        type CreatedAt = Set<members::created_at>;
        type Name = S::Name;
    }
    ///State transition - sets the `name` field to Set
    pub struct SetName<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetName<S> {}
    impl<S: State> State for SetName<S> {
        type Url = S::Url;
        type Description = S::Description;
        type AuthType = S::AuthType;
        type CreatedAt = S::CreatedAt;
        type Name = Set<members::name>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `url` field
        pub struct url(());
        ///Marker type for the `description` field
        pub struct description(());
        ///Marker type for the `auth_type` field
        pub struct auth_type(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `name` field
        pub struct name(());
    }
}

/// Builder for constructing an instance of this type
pub struct SubmissionBuilder<'a, S: submission_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Vec<CowStr<'a>>>,
        Option<SubmissionAuthType<'a>>,
        Option<Datetime>,
        Option<CowStr<'a>>,
        Option<BlobRef<'a>>,
        Option<bool>,
        Option<CowStr<'a>>,
        Option<UriValue<'a>>,
        Option<Vec<CowStr<'a>>>,
        Option<UriValue<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Submission<'a> {
    /// Create a new builder for this type
    pub fn new() -> SubmissionBuilder<'a, submission_state::Empty> {
        SubmissionBuilder::new()
    }
}

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

impl<'a, S: submission_state::State> SubmissionBuilder<'a, S> {
    /// Set the `alternativeTo` field (optional)
    pub fn alternative_to(mut self, value: impl Into<Option<Vec<CowStr<'a>>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `alternativeTo` field to an Option value (optional)
    pub fn maybe_alternative_to(mut self, value: Option<Vec<CowStr<'a>>>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<'a, S> SubmissionBuilder<'a, S>
where
    S: submission_state::State,
    S::AuthType: submission_state::IsUnset,
{
    /// Set the `authType` field (required)
    pub fn auth_type(
        mut self,
        value: impl Into<SubmissionAuthType<'a>>,
    ) -> SubmissionBuilder<'a, submission_state::SetAuthType<S>> {
        self._fields.1 = Option::Some(value.into());
        SubmissionBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

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

impl<'a, S> SubmissionBuilder<'a, S>
where
    S: submission_state::State,
    S::Description: submission_state::IsUnset,
{
    /// Set the `description` field (required)
    pub fn description(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> SubmissionBuilder<'a, submission_state::SetDescription<S>> {
        self._fields.3 = Option::Some(value.into());
        SubmissionBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: submission_state::State> SubmissionBuilder<'a, S> {
    /// Set the `icon` field (optional)
    pub fn icon(mut self, value: impl Into<Option<BlobRef<'a>>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `icon` field to an Option value (optional)
    pub fn maybe_icon(mut self, value: Option<BlobRef<'a>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<'a, S: submission_state::State> SubmissionBuilder<'a, S> {
    /// Set the `isOpenSource` field (optional)
    pub fn is_open_source(mut self, value: impl Into<Option<bool>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `isOpenSource` field to an Option value (optional)
    pub fn maybe_is_open_source(mut self, value: Option<bool>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<'a, S> SubmissionBuilder<'a, S>
where
    S: submission_state::State,
    S::Name: submission_state::IsUnset,
{
    /// Set the `name` field (required)
    pub fn name(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> SubmissionBuilder<'a, submission_state::SetName<S>> {
        self._fields.6 = Option::Some(value.into());
        SubmissionBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: submission_state::State> SubmissionBuilder<'a, S> {
    /// Set the `repositoryUrl` field (optional)
    pub fn repository_url(mut self, value: impl Into<Option<UriValue<'a>>>) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `repositoryUrl` field to an Option value (optional)
    pub fn maybe_repository_url(mut self, value: Option<UriValue<'a>>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<'a, S: submission_state::State> SubmissionBuilder<'a, S> {
    /// Set the `tags` field (optional)
    pub fn tags(mut self, value: impl Into<Option<Vec<CowStr<'a>>>>) -> Self {
        self._fields.8 = value.into();
        self
    }
    /// Set the `tags` field to an Option value (optional)
    pub fn maybe_tags(mut self, value: Option<Vec<CowStr<'a>>>) -> Self {
        self._fields.8 = value;
        self
    }
}

impl<'a, S> SubmissionBuilder<'a, S>
where
    S: submission_state::State,
    S::Url: submission_state::IsUnset,
{
    /// Set the `url` field (required)
    pub fn url(
        mut self,
        value: impl Into<UriValue<'a>>,
    ) -> SubmissionBuilder<'a, submission_state::SetUrl<S>> {
        self._fields.9 = Option::Some(value.into());
        SubmissionBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> SubmissionBuilder<'a, S>
where
    S: submission_state::State,
    S::Url: submission_state::IsSet,
    S::Description: submission_state::IsSet,
    S::AuthType: submission_state::IsSet,
    S::CreatedAt: submission_state::IsSet,
    S::Name: submission_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Submission<'a> {
        Submission {
            alternative_to: self._fields.0,
            auth_type: self._fields.1.unwrap(),
            created_at: self._fields.2.unwrap(),
            description: self._fields.3.unwrap(),
            icon: self._fields.4,
            is_open_source: self._fields.5,
            name: self._fields.6.unwrap(),
            repository_url: self._fields.7,
            tags: self._fields.8,
            url: self._fields.9.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>,
        >,
    ) -> Submission<'a> {
        Submission {
            alternative_to: self._fields.0,
            auth_type: self._fields.1.unwrap(),
            created_at: self._fields.2.unwrap(),
            description: self._fields.3.unwrap(),
            icon: self._fields.4,
            is_open_source: self._fields.5,
            name: self._fields.6.unwrap(),
            repository_url: self._fields.7,
            tags: self._fields.8,
            url: self._fields.9.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_net_alternativeproto_submission() -> 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.alternativeproto.submission"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A user submission of a project to AlternativeProto",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("name"),
                                SmolStr::new_static("description"),
                                SmolStr::new_static("url"), SmolStr::new_static("authType"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("alternativeTo"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Services this project is an alternative to",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        max_length: Some(100usize),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("authType"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Authentication method used by the project",
                                        ),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Timestamp when the submission was created",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("description"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Description of the project"),
                                    ),
                                    max_length: Some(5000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("icon"),
                                LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                            );
                            map.insert(
                                SmolStr::new_static("isOpenSource"),
                                LexObjectProperty::Boolean(LexBoolean {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("name"),
                                LexObjectProperty::String(LexString {
                                    description: Some(CowStr::new_static("The project name")),
                                    max_length: Some(200usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("repositoryUrl"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Source code repository URL"),
                                    ),
                                    format: Some(LexStringFormat::Uri),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("tags"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static("Tags for categorization"),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        max_length: Some(50usize),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("url"),
                                LexObjectProperty::String(LexString {
                                    description: Some(CowStr::new_static("The project URL")),
                                    format: Some(LexStringFormat::Uri),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}