use actix_web::{post, web, HttpResponse, Responder};
use serde::Deserialize;
use sqlx::PgPool;

use crate::{
    endpoints::user::handle_password_change_request, models::Registration, utils::ApplicationError,
};

#[derive(Deserialize)]
struct RegisterForm {
    token: String,
    password: String,
    passwordretyped: String,
    dry: Option<bool>,
}

#[post("/register")]
async fn post(
    form: web::Form<RegisterForm>,
    pool: web::Data<PgPool>,
) -> Result<impl Responder, ApplicationError> {
    // TODO: refactor into check if HX-TARGET = #password-strength exists
    let is_dry = form.dry.unwrap_or(false);
    let token =
        if let Some(token) = Registration::does_token_exist(pool.get_ref(), &form.token).await? {
            token
        } else {
            return Ok(HttpResponse::NoContent().finish());
        };

    let response = handle_password_change_request(
        pool.get_ref(),
        Some(&token),
        token.userid,
        &form.password,
        &form.passwordretyped,
        None,
        is_dry,
    )
    .await?;

    Ok(response)
}
