// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: com.atproto.server.createAppPassword
//
// 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::string::Datetime;
use jacquard_derive::{IntoStatic, lexicon, open_union};
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::com_atproto::server::create_app_password;

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct AppPassword<'a> {
    pub created_at: Datetime,
    #[serde(borrow)]
    pub name: CowStr<'a>,
    #[serde(borrow)]
    pub password: CowStr<'a>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub privileged: Option<bool>,
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct CreateAppPassword<'a> {
    ///A short name for the App Password, to help distinguish them.
    #[serde(borrow)]
    pub name: CowStr<'a>,
    ///If an app password has 'privileged' access to possibly sensitive account state. Meant for use with trusted clients.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub privileged: Option<bool>,
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct CreateAppPasswordOutput<'a> {
    #[serde(flatten)]
    #[serde(borrow)]
    pub value: jacquard_common::types::value::Data<'a>,
}


#[open_union]
#[derive(
    Serialize,
    Deserialize,
    Debug,
    Clone,
    PartialEq,
    Eq,
    thiserror::Error,
    miette::Diagnostic,
    IntoStatic
)]

#[serde(tag = "error", content = "message")]
#[serde(bound(deserialize = "'de: 'a"))]
pub enum CreateAppPasswordError<'a> {
    #[serde(rename = "AccountTakedown")]
    AccountTakedown(Option<CowStr<'a>>),
}

impl core::fmt::Display for CreateAppPasswordError<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::AccountTakedown(msg) => {
                write!(f, "AccountTakedown")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::Unknown(err) => write!(f, "Unknown error: {:?}", err),
        }
    }
}

impl<'a> LexiconSchema for AppPassword<'a> {
    fn nsid() -> &'static str {
        "com.atproto.server.createAppPassword"
    }
    fn def_name() -> &'static str {
        "appPassword"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_com_atproto_server_createAppPassword()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

/// Response type for com.atproto.server.createAppPassword
pub struct CreateAppPasswordResponse;
impl jacquard_common::xrpc::XrpcResp for CreateAppPasswordResponse {
    const NSID: &'static str = "com.atproto.server.createAppPassword";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = CreateAppPasswordOutput<'de>;
    type Err<'de> = CreateAppPasswordError<'de>;
}

impl<'a> jacquard_common::xrpc::XrpcRequest for CreateAppPassword<'a> {
    const NSID: &'static str = "com.atproto.server.createAppPassword";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Procedure(
        "application/json",
    );
    type Response = CreateAppPasswordResponse;
}

/// Endpoint type for com.atproto.server.createAppPassword
pub struct CreateAppPasswordRequest;
impl jacquard_common::xrpc::XrpcEndpoint for CreateAppPasswordRequest {
    const PATH: &'static str = "/xrpc/com.atproto.server.createAppPassword";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Procedure(
        "application/json",
    );
    type Request<'de> = CreateAppPassword<'de>;
    type Response = CreateAppPasswordResponse;
}

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

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

impl<'a> AppPassword<'a> {
    /// Create a new builder for this type
    pub fn new() -> AppPasswordBuilder<'a, app_password_state::Empty> {
        AppPasswordBuilder::new()
    }
}

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

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

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

impl<'a, S> AppPasswordBuilder<'a, S>
where
    S: app_password_state::State,
    S::Password: app_password_state::IsUnset,
{
    /// Set the `password` field (required)
    pub fn password(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> AppPasswordBuilder<'a, app_password_state::SetPassword<S>> {
        self._fields.2 = Option::Some(value.into());
        AppPasswordBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: app_password_state::State> AppPasswordBuilder<'a, S> {
    /// Set the `privileged` field (optional)
    pub fn privileged(mut self, value: impl Into<Option<bool>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `privileged` field to an Option value (optional)
    pub fn maybe_privileged(mut self, value: Option<bool>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<'a, S> AppPasswordBuilder<'a, S>
where
    S: app_password_state::State,
    S::Password: app_password_state::IsSet,
    S::Name: app_password_state::IsSet,
    S::CreatedAt: app_password_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> AppPassword<'a> {
        AppPassword {
            created_at: self._fields.0.unwrap(),
            name: self._fields.1.unwrap(),
            password: self._fields.2.unwrap(),
            privileged: self._fields.3,
            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>,
        >,
    ) -> AppPassword<'a> {
        AppPassword {
            created_at: self._fields.0.unwrap(),
            name: self._fields.1.unwrap(),
            password: self._fields.2.unwrap(),
            privileged: self._fields.3,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_com_atproto_server_createAppPassword() -> 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("com.atproto.server.createAppPassword"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("appPassword"),
                LexUserType::Object(LexObject {
                    required: Some(
                        vec![
                            SmolStr::new_static("name"), SmolStr::new_static("password"),
                            SmolStr::new_static("createdAt")
                        ],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("createdAt"),
                            LexObjectProperty::String(LexString {
                                format: Some(LexStringFormat::Datetime),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("name"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map.insert(
                            SmolStr::new_static("password"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map.insert(
                            SmolStr::new_static("privileged"),
                            LexObjectProperty::Boolean(LexBoolean {
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::XrpcProcedure(LexXrpcProcedure {
                    input: Some(LexXrpcBody {
                        encoding: CowStr::new_static("application/json"),
                        schema: Some(
                            LexXrpcBodySchema::Object(LexObject {
                                required: Some(vec![SmolStr::new_static("name")]),
                                properties: {
                                    #[allow(unused_mut)]
                                    let mut map = BTreeMap::new();
                                    map.insert(
                                        SmolStr::new_static("name"),
                                        LexObjectProperty::String(LexString {
                                            description: Some(
                                                CowStr::new_static(
                                                    "A short name for the App Password, to help distinguish them.",
                                                ),
                                            ),
                                            ..Default::default()
                                        }),
                                    );
                                    map.insert(
                                        SmolStr::new_static("privileged"),
                                        LexObjectProperty::Boolean(LexBoolean {
                                            ..Default::default()
                                        }),
                                    );
                                    map
                                },
                                ..Default::default()
                            }),
                        ),
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}