use crate::{
    models::{Area, Function, Role, User},
    utils::ApplicationError,
};

use actix_web::{web, HttpResponse, Responder};
use rinja::Template;
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: web::ReqData<User>,
    pool: web::Data<PgPool>,
) -> Result<impl Responder, ApplicationError> {
    if user.role != Role::AreaManager && user.role != Role::Admin {
        return Err(ApplicationError::Unauthorized);
    }

    let mut area = None;
    let users;

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

    let template = UsersTemplate {
        user: user.into_inner(),
        area,
        users,
    };

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