use actix_web::{web, HttpResponse, Responder};
use rinja::Template;
use sqlx::PgPool;

use crate::{
    endpoints::user::NewOrEditUserTemplate,
    models::{Area, Role, User},
    utils::ApplicationError,
};

#[actix_web::get("/users/new")]
pub async fn get_new(
    user: web::ReqData<User>,
    pool: web::Data<PgPool>,
) -> Result<impl Responder, ApplicationError> {
    let mut areas: Option<Vec<Area>> = None;

    if user.role == Role::Admin {
        areas = Some(Area::read_all(pool.get_ref()).await?)
    }

    let template = NewOrEditUserTemplate {
        user: user.into_inner(),
        areas,
        id: None,
        email: None,
        name: None,
        role: None,
        function: None,
        area_id: None,
    };

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