use crate::{
    endpoints::area::NewOrEditAreaTemplate,
    models::{Role, User},
    utils::ApplicationError,
};
use actix_web::{web, HttpResponse, Responder};
use brass_macros::db_test;
use rinja::Template;

#[cfg(test)]
use crate::utils::test_helper::{
    assert_snapshot, read_body, test_get, DbTestContext, RequestConfig,
};
#[cfg(test)]
use actix_http::StatusCode;

#[actix_web::get("/area/new")]
async fn get(user: web::ReqData<User>) -> Result<impl Responder, ApplicationError> {
    if user.role != Role::Admin {
        return Err(ApplicationError::Unauthorized);
    }

    let template = NewOrEditAreaTemplate {
        user: user.into_inner(),
        area: None,
    };

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

#[db_test]
async fn produces_template(context: &DbTestContext) {
    let app = context.app().await;
    let config = RequestConfig {
        uri: "/area/new".to_string(),
        role: Role::Admin,
        function: crate::models::Function::Posten,
        user_area: 1,
    };
    let response = test_get(&context.db_pool, app, &config).await;

    assert_eq!(StatusCode::OK, response.status());

    let body = read_body(response).await;
    assert_snapshot!(body);
}
