use crate::models::{Area, Role, User, Function};
use actix_identity::Identity;
use actix_web::{web, HttpResponse, Responder};
use askama::Template;
use askama_actix::TemplateToResponse;
use sqlx::PgPool;

#[derive(Template)]
#[template(path = "user/overview.html")]
pub struct UsersTemplate {
    user: User,
    area: Option<Area>,
    users: Vec<User>,
}

#[actix_web::get("/users")]
pub async fn get_overview(user: Identity, pool: web::Data<PgPool>) -> impl Responder {
    let current_user = User::read_by_id(pool.get_ref(), user.id().unwrap().parse().unwrap())
        .await
        .unwrap();

    if current_user.role == Role::AreaManager || current_user.role == Role::Admin {
        let mut area = None;
        let users;

        if current_user.role == Role::AreaManager {
            area = Some(
                Area::read_by_id(pool.get_ref(), current_user.area_id)
                    .await
                    .unwrap().unwrap(),
            );
            users = User::read_all_by_area(pool.get_ref(), current_user.area_id)
                .await
                .unwrap();
        } else {
            users = User::read_all_including_area(pool.get_ref()).await.unwrap();
        }

        let template = UsersTemplate {
            user: current_user,
            area,
            users,
        };

        return template.to_response();
    }

    return HttpResponse::BadRequest().body("Fehler beim Zugriff auf die Nutzerverwaltung!");
}
