// @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;
use jacquard_common::types::string::{Did, Handle};
use jacquard_common::types::value::Data;
use jacquard_derive::{IntoStatic, lexicon, open_union};
use serde::{Serialize, Deserialize};

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct CreateAccount<'a> {
    ///Pre-existing atproto DID, being imported to a new account.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub did: Option<Did<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub email: Option<CowStr<'a>>,
    ///Requested handle for the account.
    #[serde(borrow)]
    pub handle: Handle<'a>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub invite_code: Option<CowStr<'a>>,
    ///Initial account password. May need to meet instance-specific password strength requirements.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub password: Option<CowStr<'a>>,
    ///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")]
    #[serde(borrow)]
    pub plc_op: Option<Data<'a>>,
    ///DID PLC rotation key (aka, recovery key) to be included in PLC creation operation.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub recovery_key: Option<CowStr<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub verification_code: Option<CowStr<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub verification_phone: Option<CowStr<'a>>,
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct CreateAccountOutput<'a> {
    #[serde(borrow)]
    pub access_jwt: CowStr<'a>,
    ///The DID of the new account.
    #[serde(borrow)]
    pub did: Did<'a>,
    ///Complete DID document.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub did_doc: Option<Data<'a>>,
    #[serde(borrow)]
    pub handle: Handle<'a>,
    #[serde(borrow)]
    pub refresh_jwt: CowStr<'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 CreateAccountError<'a> {
    #[serde(rename = "InvalidHandle")]
    InvalidHandle(Option<CowStr<'a>>),
    #[serde(rename = "InvalidPassword")]
    InvalidPassword(Option<CowStr<'a>>),
    #[serde(rename = "InvalidInviteCode")]
    InvalidInviteCode(Option<CowStr<'a>>),
    #[serde(rename = "HandleNotAvailable")]
    HandleNotAvailable(Option<CowStr<'a>>),
    #[serde(rename = "UnsupportedDomain")]
    UnsupportedDomain(Option<CowStr<'a>>),
    #[serde(rename = "UnresolvableDid")]
    UnresolvableDid(Option<CowStr<'a>>),
    #[serde(rename = "IncompatibleDidDoc")]
    IncompatibleDidDoc(Option<CowStr<'a>>),
}

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::Unknown(err) => write!(f, "Unknown error: {:?}", err),
        }
    }
}

/// Response type for com.atproto.server.createAccount
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<'de> = CreateAccountOutput<'de>;
    type Err<'de> = CreateAccountError<'de>;
}

impl<'a> jacquard_common::xrpc::XrpcRequest for CreateAccount<'a> {
    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 type for com.atproto.server.createAccount
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<'de> = CreateAccount<'de>;
    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<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetHandle<S> {}
    impl<S: State> State for SetHandle<S> {
        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<'a, S: create_account_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Did<'a>>,
        Option<CowStr<'a>>,
        Option<Handle<'a>>,
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
        Option<Data<'a>>,
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

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

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

impl<'a, S: create_account_state::State> CreateAccountBuilder<'a, S> {
    /// Set the `did` field (optional)
    pub fn did(mut self, value: impl Into<Option<Did<'a>>>) -> 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<'a>>) -> Self {
        self._fields.0 = value;
        self
    }
}

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

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

impl<'a, S: create_account_state::State> CreateAccountBuilder<'a, S> {
    /// Set the `inviteCode` field (optional)
    pub fn invite_code(mut self, value: impl Into<Option<CowStr<'a>>>) -> 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<CowStr<'a>>) -> Self {
        self._fields.3 = value;
        self
    }
}

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

impl<'a, S: create_account_state::State> CreateAccountBuilder<'a, S> {
    /// Set the `plcOp` field (optional)
    pub fn plc_op(mut self, value: impl Into<Option<Data<'a>>>) -> 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<'a>>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<'a, S: create_account_state::State> CreateAccountBuilder<'a, S> {
    /// Set the `recoveryKey` field (optional)
    pub fn recovery_key(mut self, value: impl Into<Option<CowStr<'a>>>) -> 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<CowStr<'a>>) -> Self {
        self._fields.6 = value;
        self
    }
}

impl<'a, S: create_account_state::State> CreateAccountBuilder<'a, S> {
    /// Set the `verificationCode` field (optional)
    pub fn verification_code(mut self, value: impl Into<Option<CowStr<'a>>>) -> 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<CowStr<'a>>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<'a, S: create_account_state::State> CreateAccountBuilder<'a, S> {
    /// Set the `verificationPhone` field (optional)
    pub fn verification_phone(mut self, value: impl Into<Option<CowStr<'a>>>) -> 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<CowStr<'a>>) -> Self {
        self._fields.8 = value;
        self
    }
}

impl<'a, S> CreateAccountBuilder<'a, S>
where
    S: create_account_state::State,
    S::Handle: create_account_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> CreateAccount<'a> {
        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<jacquard_common::deps::smol_str::SmolStr, Data<'a>>,
    ) -> CreateAccount<'a> {
        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),
        }
    }
}