// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: com.atproto.server.createAccount
//
// 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};
use jacquard_common::deps::smol_str::SmolStr;
use jacquard_common::types::string::{Did, Handle};
use jacquard_common::types::value::Data;
use jacquard_derive::{IntoStatic, open_union};
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct CreateAccount<S: BosStr = DefaultStr> {
    ///Pre-existing atproto DID, being imported to a new account.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub did: Option<Did<S>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<S>,
    ///Requested handle for the account.
    pub handle: Handle<S>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub invite_code: Option<S>,
    ///Initial account password. May need to meet instance-specific password strength requirements.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub password: Option<S>,
    ///A signed DID PLC operation to be submitted as part of importing an existing account to this instance. NOTE: this optional field may be updated when full account migration is implemented.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub plc_op: Option<Data<S>>,
    ///DID PLC rotation key (aka, recovery key) to be included in PLC creation operation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recovery_key: Option<S>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub verification_code: Option<S>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub verification_phone: Option<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, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct CreateAccountOutput<S: BosStr = DefaultStr> {
    pub access_jwt: S,
    ///The DID of the new account.
    pub did: Did<S>,
    ///Complete DID document.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub did_doc: Option<Data<S>>,
    pub handle: Handle<S>,
    pub refresh_jwt: 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 CreateAccountError {
    #[serde(rename = "InvalidHandle")]
    InvalidHandle(Option<SmolStr>),
    #[serde(rename = "InvalidPassword")]
    InvalidPassword(Option<SmolStr>),
    #[serde(rename = "InvalidInviteCode")]
    InvalidInviteCode(Option<SmolStr>),
    #[serde(rename = "HandleNotAvailable")]
    HandleNotAvailable(Option<SmolStr>),
    #[serde(rename = "UnsupportedDomain")]
    UnsupportedDomain(Option<SmolStr>),
    #[serde(rename = "UnresolvableDid")]
    UnresolvableDid(Option<SmolStr>),
    #[serde(rename = "IncompatibleDidDoc")]
    IncompatibleDidDoc(Option<SmolStr>),
    /// Catch-all for unknown error codes.
    #[serde(untagged)]
    Other { error: SmolStr, message: Option<SmolStr> },
}

impl core::fmt::Display for CreateAccountError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::InvalidHandle(msg) => {
                write!(f, "InvalidHandle")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::InvalidPassword(msg) => {
                write!(f, "InvalidPassword")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::InvalidInviteCode(msg) => {
                write!(f, "InvalidInviteCode")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::HandleNotAvailable(msg) => {
                write!(f, "HandleNotAvailable")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::UnsupportedDomain(msg) => {
                write!(f, "UnsupportedDomain")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::UnresolvableDid(msg) => {
                write!(f, "UnresolvableDid")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::IncompatibleDidDoc(msg) => {
                write!(f, "IncompatibleDidDoc")?;
                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(())
            }
        }
    }
}

/** Response marker for the `com.atproto.server.createAccount` procedure.

Implements `jacquard_common::xrpc::XrpcResp`; successful bodies decode as `Self::Output<S>`, which is `CreateAccountOutput<S>` for this endpoint.*/
pub struct CreateAccountResponse;
impl jacquard_common::xrpc::XrpcResp for CreateAccountResponse {
    const NSID: &'static str = "com.atproto.server.createAccount";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = CreateAccountOutput<S>;
    type Err = CreateAccountError;
}

impl<S: BosStr> jacquard_common::xrpc::XrpcRequest for CreateAccount<S> {
    const NSID: &'static str = "com.atproto.server.createAccount";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Procedure(
        "application/json",
    );
    type Response = CreateAccountResponse;
}

/** Endpoint marker for the `com.atproto.server.createAccount` procedure.

Path: `/xrpc/com.atproto.server.createAccount`. The request payload type is `CreateAccount<S>`; send that request with `jacquard::Client` or use this marker through lower-level `XrpcEndpoint` APIs.*/
pub struct CreateAccountRequest;
impl jacquard_common::xrpc::XrpcEndpoint for CreateAccountRequest {
    const PATH: &'static str = "/xrpc/com.atproto.server.createAccount";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Procedure(
        "application/json",
    );
    type Request<S: BosStr> = CreateAccount<S>;
    type Response = CreateAccountResponse;
}

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

/// Builder for constructing an instance of this type.
pub struct CreateAccountBuilder<
    St: create_account_state::State,
    S: BosStr = DefaultStr,
> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Did<S>>,
        Option<S>,
        Option<Handle<S>>,
        Option<S>,
        Option<S>,
        Option<Data<S>>,
        Option<S>,
        Option<S>,
        Option<S>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> CreateAccount<S> {
    /// Create a new builder for this type
    pub fn builder() -> CreateAccountBuilder<create_account_state::Empty, S> {
        CreateAccountBuilder::builder()
    }
}

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

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

impl<St: create_account_state::State, S: BosStr> CreateAccountBuilder<St, S> {
    /// Set the `did` field (optional)
    pub fn did(mut self, value: impl Into<Option<Did<S>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `did` field to an Option value (optional)
    pub fn maybe_did(mut self, value: Option<Did<S>>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St: create_account_state::State, S: BosStr> CreateAccountBuilder<St, S> {
    /// Set the `email` field (optional)
    pub fn email(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `email` field to an Option value (optional)
    pub fn maybe_email(mut self, value: Option<S>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<St, S: BosStr> CreateAccountBuilder<St, S>
where
    St: create_account_state::State,
    St::Handle: create_account_state::IsUnset,
{
    /// Set the `handle` field (required)
    pub fn handle(
        mut self,
        value: impl Into<Handle<S>>,
    ) -> CreateAccountBuilder<create_account_state::SetHandle<St>, S> {
        self._fields.2 = Option::Some(value.into());
        CreateAccountBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: create_account_state::State, S: BosStr> CreateAccountBuilder<St, S> {
    /// Set the `inviteCode` field (optional)
    pub fn invite_code(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `inviteCode` field to an Option value (optional)
    pub fn maybe_invite_code(mut self, value: Option<S>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St: create_account_state::State, S: BosStr> CreateAccountBuilder<St, S> {
    /// Set the `password` field (optional)
    pub fn password(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `password` field to an Option value (optional)
    pub fn maybe_password(mut self, value: Option<S>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St: create_account_state::State, S: BosStr> CreateAccountBuilder<St, S> {
    /// Set the `plcOp` field (optional)
    pub fn plc_op(mut self, value: impl Into<Option<Data<S>>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `plcOp` field to an Option value (optional)
    pub fn maybe_plc_op(mut self, value: Option<Data<S>>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<St: create_account_state::State, S: BosStr> CreateAccountBuilder<St, S> {
    /// Set the `recoveryKey` field (optional)
    pub fn recovery_key(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.6 = value.into();
        self
    }
    /// Set the `recoveryKey` field to an Option value (optional)
    pub fn maybe_recovery_key(mut self, value: Option<S>) -> Self {
        self._fields.6 = value;
        self
    }
}

impl<St: create_account_state::State, S: BosStr> CreateAccountBuilder<St, S> {
    /// Set the `verificationCode` field (optional)
    pub fn verification_code(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `verificationCode` field to an Option value (optional)
    pub fn maybe_verification_code(mut self, value: Option<S>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<St: create_account_state::State, S: BosStr> CreateAccountBuilder<St, S> {
    /// Set the `verificationPhone` field (optional)
    pub fn verification_phone(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.8 = value.into();
        self
    }
    /// Set the `verificationPhone` field to an Option value (optional)
    pub fn maybe_verification_phone(mut self, value: Option<S>) -> Self {
        self._fields.8 = value;
        self
    }
}

impl<St, S: BosStr> CreateAccountBuilder<St, S>
where
    St: create_account_state::State,
    St::Handle: create_account_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> CreateAccount<S> {
        CreateAccount {
            did: self._fields.0,
            email: self._fields.1,
            handle: self._fields.2.unwrap(),
            invite_code: self._fields.3,
            password: self._fields.4,
            plc_op: self._fields.5,
            recovery_key: self._fields.6,
            verification_code: self._fields.7,
            verification_phone: self._fields.8,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(
        self,
        extra_data: BTreeMap<SmolStr, Data<S>>,
    ) -> CreateAccount<S> {
        CreateAccount {
            did: self._fields.0,
            email: self._fields.1,
            handle: self._fields.2.unwrap(),
            invite_code: self._fields.3,
            password: self._fields.4,
            plc_op: self._fields.5,
            recovery_key: self._fields.6,
            verification_code: self._fields.7,
            verification_phone: self._fields.8,
            extra_data: Some(extra_data),
        }
    }
}