use actix_web::{web, HttpResponse, Responder};
use brass_macros::db_test;
use sqlx::PgPool;

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

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

#[actix_web::delete("/area/delete/{id}")]
pub async fn delete(
    user: web::ReqData<User>,
    pool: web::Data<PgPool>,
    path: web::Path<IdPath>,
) -> Result<impl Responder, ApplicationError> {
    if user.role != Role::Admin {
        return Err(ApplicationError::Unauthorized);
    }

    if Area::read_by_id(pool.get_ref(), path.id).await?.is_none() {
        return Ok(HttpResponse::NotFound().finish());
    };

    Area::delete(pool.get_ref(), path.id).await?;

    return Ok(HttpResponse::Ok().finish());
}

#[db_test]
async fn works_when_user_is_admin(context: &DbTestContext) {
    Area::create(&context.db_pool, "Area to delete")
        .await
        .unwrap();
    assert!(Area::read_by_id(&context.db_pool, 2)
        .await
        .unwrap()
        .is_some());

    let app = context.app().await;
    let config = RequestConfig {
        uri: "/area/delete/2".to_string(),
        role: Role::Admin,
        function: crate::models::Function::Posten,
        user_area: 1,
    };
    let response = test_delete(&context.db_pool, app, &config).await;

    assert_eq!(StatusCode::OK, response.status());
    assert!(Area::read_by_id(&context.db_pool, 2)
        .await
        .unwrap()
        .is_none());
}

#[db_test]
async fn does_not_work_when_user_is_not_admin(context: &DbTestContext) {
    Area::create(&context.db_pool, "Area to delete")
        .await
        .unwrap();
    assert!(Area::read_by_id(&context.db_pool, 2)
        .await
        .unwrap()
        .is_some());

    let app = context.app().await;
    let response = test_delete(&context.db_pool, app, &RequestConfig::new("/area/delete/2")).await;

    assert_eq!(StatusCode::UNAUTHORIZED, response.status());
    assert!(Area::read_by_id(&context.db_pool, 2)
        .await
        .unwrap()
        .is_some());
}
