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::Registration, utils::ApplicationError};

use super::ResetPasswordTemplate;

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

#[get("/register")]
pub async fn get(
    user: Option<Identity>,
    pool: web::Data<PgPool>,
    query: web::Query<TokenQuery>,
) -> Result<impl Responder, ApplicationError> {
    if user.is_some() {
        return Ok(HttpResponse::Found()
            .insert_header((LOCATION, "/"))
            .finish());
    }

    let Some(_) = Registration::does_token_exist(pool.get_ref(), &query.token).await? else {
        return Ok(HttpResponse::NotFound().finish());
    };

    let template = ResetPasswordTemplate {
        token: &query.token,
        title: "Brass - Registrierung",
        endpoint: "/register",
        new_password_label: "Passwort:",
        retype_label: "Passwort wiederholen:",
        submit_button_label: "Registrieren",
    };

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