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

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

#[actix_web::get("/users/edit/{id}")]
pub async fn get_edit(
    user: web::ReqData<User>,
    pool: web::Data<PgPool>,
    path: web::Path<IdPath>,
) -> Result<impl Responder, ApplicationError> {
    let mut areas = None;

    if user.role != Role::AreaManager && user.role != Role::Admin {
        return Err(ApplicationError::Unauthorized);
    }

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

    let Some(user_in_db) = User::read_by_id(pool.get_ref(), path.id).await? else {
        return Ok(HttpResponse::NotFound().finish());
    };

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

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