use actix_identity::Identity;
use actix_web::{get, http::header::LOCATION, web, HttpResponse, Responder};
use askama_actix::TemplateToResponse;
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());
    }

    if let Some(_) = Registration::does_token_exist(pool.get_ref(), &query.token).await? {
        let template = ResetPasswordTemplate {
            token: &query.token,
            title: "Brass - Registrierung",
            endpoint: "/register",
            new_password_label: "Passwort:",
            retype_label: "Passwort wiederholen:",
            submit_button_label: "Registrieren",
        };

        return Ok(template.to_response());
    }

    Ok(HttpResponse::NotFound().finish())
}
