// @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, 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::string::Datetime;
use jacquard_common::types::value::Data;
use jacquard_derive::{IntoStatic, 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;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct AppPassword<S: BosStr = DefaultStr> {
    pub created_at: Datetime,
    pub name: S,
    pub password: S,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub privileged: Option<bool>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct CreateAppPassword<S: BosStr = DefaultStr> {
    ///A short name for the App Password, to help distinguish them.
    pub name: S,
    ///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>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct CreateAppPasswordOutput<S: BosStr = DefaultStr> {
    #[serde(flatten)]
    pub value: Data<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


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

#[serde(tag = "error", content = "message")]
pub enum CreateAppPasswordError {
    #[serde(rename = "AccountTakedown")]
    AccountTakedown(Option<SmolStr>),
    /// Catch-all for unknown error codes.
    #[serde(untagged)]
    Other { error: SmolStr, message: Option<SmolStr> },
}

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::Other { error, message } => {
                write!(f, "{}", error)?;
                if let Some(msg) = message {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
        }
    }
}

impl<S: BosStr> LexiconSchema for AppPassword<S> {
    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 marker for the `com.atproto.server.createAppPassword` procedure.

Implements `jacquard_common::xrpc::XrpcResp`; successful bodies decode as `Self::Output<S>`, which is `CreateAppPasswordOutput<S>` for this endpoint.*/
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<S: BosStr> = CreateAppPasswordOutput<S>;
    type Err = CreateAppPasswordError;
}

impl<S: BosStr> jacquard_common::xrpc::XrpcRequest for CreateAppPassword<S> {
    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 marker for the `com.atproto.server.createAppPassword` procedure.

Path: `/xrpc/com.atproto.server.createAppPassword`. The request payload type is `CreateAppPassword<S>`; send that request with `jacquard::Client` or use this marker through lower-level `XrpcEndpoint` APIs.*/
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<S: BosStr> = CreateAppPassword<S>;
    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 CreatedAt;
        type Name;
        type Password;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedAt = Unset;
        type Name = Unset;
        type Password = Unset;
    }
    ///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 CreatedAt = Set<members::created_at>;
        type Name = St::Name;
        type Password = St::Password;
    }
    ///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 CreatedAt = St::CreatedAt;
        type Name = Set<members::name>;
        type Password = St::Password;
    }
    ///State transition - sets the `password` field to Set
    pub struct SetPassword<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetPassword<St> {}
    impl<St: State> State for SetPassword<St> {
        type CreatedAt = St::CreatedAt;
        type Name = St::Name;
        type Password = Set<members::password>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `name` field
        pub struct name(());
        ///Marker type for the `password` field
        pub struct password(());
    }
}

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

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

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

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

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

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

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

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

impl<St: app_password_state::State, S: BosStr> AppPasswordBuilder<St, 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<St, S: BosStr> AppPasswordBuilder<St, S>
where
    St: app_password_state::State,
    St::CreatedAt: app_password_state::IsSet,
    St::Name: app_password_state::IsSet,
    St::Password: app_password_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> AppPassword<S> {
        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<SmolStr, Data<S>>,
    ) -> AppPassword<S> {
        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()
    }
}