use actix_identity::Identity;
use actix_web::{web, HttpMessage, HttpRequest, HttpResponse, Responder};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;

use crate::{auth::utils::hash_plain_password_with_salt, models::User};

#[derive(Deserialize, Serialize)]
pub struct LoginForm {
    pub email: String,
    pub password: String,
}

#[actix_web::post("/login")]
async fn post(
    web::Form(form): web::Form<LoginForm>,
    request: HttpRequest,
    pool: web::Data<PgPool>,
) -> impl Responder {
    if let Ok(user) = User::read_for_login(pool.get_ref(), &form.email).await {
        let salt = user.salt.unwrap();

        let hash = hash_plain_password_with_salt(&form.password, &salt).unwrap();
        if hash == user.password.unwrap() {
            Identity::login(&request.extensions(), user.id.to_string()).unwrap();

            User::update_login_timestamp(pool.get_ref(), user.id)
                .await
                .unwrap();

            return HttpResponse::Found()
                .insert_header(("LOCATION", "/"))
                .insert_header(("HX-LOCATION", "/"))
                .finish();
        }
    }

    return HttpResponse::BadRequest().body("E-Mail oder Passwort falsch.");
}
