use actix_identity::Identity;
use actix_web::{get, http::header::LOCATION, web, HttpResponse, Responder};
use rinja::Template;
use serde::Deserialize;
use sqlx::PgPool;

use crate::{models::PasswordReset, utils::ApplicationError};

use super::ResetPasswordTemplate;

#[derive(Template)]
#[template(path = "user/forgot_password.html")]
struct ForgotPasswordTemplate {}

#[derive(Deserialize)]
struct TokenQuery {
    token: Option<String>,
}

#[get("/reset-password")]
pub async fn get(
    user: Option<Identity>,
    pool: web::Data<PgPool>,
    query: web::Query<TokenQuery>,
) -> Result<impl Responder, ApplicationError> {
    if let Some(_) = user {
        return Ok(HttpResponse::Found()
            .insert_header((LOCATION, "/"))
            .finish());
    } else if let Some(token) = &query.token {
        if let Some(_) = PasswordReset::does_token_exist(pool.get_ref(), token).await? {
            let template = ResetPasswordTemplate {
                token,
                title: "Brass - Passwort zurücksetzen",
                endpoint: "/reset-password",
                new_password_label: "neues Passwort:",
                retype_label: "neues Passwort wiederholen:",
                submit_button_label: "Passwort zurücksetzen",
            };

            return Ok(HttpResponse::Ok().body(template.render()?))
        }
    }

    let template = ForgotPasswordTemplate {};
    Ok(HttpResponse::Ok().body(template.render()?))
}
