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

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

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

#[actix_web::post("/users/changepassword")]
async fn post(
    user: web::ReqData<User>,
    form: web::Form<ChangePasswordForm>,
    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 response = handle_password_change_request(
        pool.get_ref(),
        None::<&NoneToken>,
        user.id,
        &form.password,
        &form.passwordretyped,
        Some(&form.currentpassword),
        is_dry,
    )
    .await?;

    return Ok(response);
}
