// @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, 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, Datetime, UriValue};
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 user submission of a project to AlternativeProto

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "net.alternativeproto.submission",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Submission<S: BosStr = DefaultStr> {
    ///Services this project is an alternative to
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alternative_to: Option<Vec<S>>,
    ///Authentication method used by the project
    pub auth_type: SubmissionAuthType<S>,
    ///Timestamp when the submission was created
    pub created_at: Datetime,
    ///Description of the project
    pub description: S,
    ///Project icon image blob
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon: Option<BlobRef<S>>,
    ///Whether the project is open source
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_open_source: Option<bool>,
    ///The project name
    pub name: S,
    ///Source code repository URL
    #[serde(skip_serializing_if = "Option::is_none")]
    pub repository_url: Option<UriValue<S>>,
    ///Tags for categorization
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<S>>,
    ///The project URL
    pub url: UriValue<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// Authentication method used by the project

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SubmissionAuthType<S: BosStr = DefaultStr> {
    Oauth,
    AppPassword,
    None,
    Other(S),
}

impl<S: BosStr> SubmissionAuthType<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Oauth => "oauth",
            Self::AppPassword => "app-password",
            Self::None => "none",
            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() {
            "oauth" => Self::Oauth,
            "app-password" => Self::AppPassword,
            "none" => Self::None,
            _ => Self::Other(s),
        }
    }
}

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

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

impl<S: BosStr> Serialize for SubmissionAuthType<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 SubmissionAuthType<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 SubmissionAuthType<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for SubmissionAuthType<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = SubmissionAuthType<S::Output>;
    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<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Submission<S>,
}

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

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

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

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

/// Builder for constructing an instance of this type.
pub struct SubmissionBuilder<St: submission_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Vec<S>>,
        Option<SubmissionAuthType<S>>,
        Option<Datetime>,
        Option<S>,
        Option<BlobRef<S>>,
        Option<bool>,
        Option<S>,
        Option<UriValue<S>>,
        Option<Vec<S>>,
        Option<UriValue<S>>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

impl<St: submission_state::State, S: BosStr> SubmissionBuilder<St, S> {
    /// Set the `alternativeTo` field (optional)
    pub fn alternative_to(mut self, value: impl Into<Option<Vec<S>>>) -> 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<S>>) -> Self {
        self._fields.0 = value;
        self
    }
}

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

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

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

impl<St: submission_state::State, S: BosStr> SubmissionBuilder<St, S> {
    /// Set the `icon` field (optional)
    pub fn icon(mut self, value: impl Into<Option<BlobRef<S>>>) -> 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<S>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St: submission_state::State, S: BosStr> SubmissionBuilder<St, 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<St, S: BosStr> SubmissionBuilder<St, S>
where
    St: submission_state::State,
    St::Name: submission_state::IsUnset,
{
    /// Set the `name` field (required)
    pub fn name(
        mut self,
        value: impl Into<S>,
    ) -> SubmissionBuilder<submission_state::SetName<St>, S> {
        self._fields.6 = Option::Some(value.into());
        SubmissionBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: submission_state::State, S: BosStr> SubmissionBuilder<St, S> {
    /// Set the `repositoryUrl` field (optional)
    pub fn repository_url(mut self, value: impl Into<Option<UriValue<S>>>) -> 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<S>>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<St: submission_state::State, S: BosStr> SubmissionBuilder<St, S> {
    /// Set the `tags` field (optional)
    pub fn tags(mut self, value: impl Into<Option<Vec<S>>>) -> 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<S>>) -> Self {
        self._fields.8 = value;
        self
    }
}

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

impl<St, S: BosStr> SubmissionBuilder<St, S>
where
    St: submission_state::State,
    St::AuthType: submission_state::IsSet,
    St::CreatedAt: submission_state::IsSet,
    St::Description: submission_state::IsSet,
    St::Name: submission_state::IsSet,
    St::Url: submission_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Submission<S> {
        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<SmolStr, Data<S>>,
    ) -> Submission<S> {
        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()
    }
}