//! Account handler — account deletion.

use std::sync::Arc;

use bytes::Bytes;
use prost::Message;
use quicproquo_proto::qpq::v1;
use quicproquo_rpc::method::{HandlerResult, RequestContext};

use crate::domain::account::AccountService;

use super::{domain_err, require_auth, ServerState};

pub async fn handle_delete_account(
    state: Arc<ServerState>,
    ctx: RequestContext,
) -> HandlerResult {
    let identity_key = match require_auth(&state, &ctx) {
        Ok(ik) => ik,
        Err(e) => return e,
    };

    // DeleteAccountRequest is empty but decode for protocol correctness.
    let _req = match v1::DeleteAccountRequest::decode(ctx.payload) {
        Ok(r) => r,
        Err(e) => {
            return HandlerResult::err(
                quicproquo_rpc::error::RpcStatus::BadRequest,
                &format!("decode: {e}"),
            )
        }
    };

    let svc = AccountService {
        store: Arc::clone(&state.store),
        kt_log: Arc::clone(&state.kt_log),
    };

    match svc.delete_account(&identity_key) {
        Ok(()) => {
            // Remove session for the deleted account.
            if let Some(token) = ctx.session_token.as_deref() {
                state.sessions.remove(token);
            }

            let proto = v1::DeleteAccountResponse { success: true };
            HandlerResult::ok(Bytes::from(proto.encode_to_vec()))
        }
        Err(e) => domain_err(e),
    }
}
