use actix_web::{http::header::LOCATION, web, HttpResponse, Responder};
use sqlx::PgPool;

use crate::{
    endpoints::location::LocationForm,
    models::{Location, Role, User}, utils::ApplicationError,
};

#[actix_web::post("/locations/new")]
pub async fn post(
    user: web::ReqData<User>,
    pool: web::Data<PgPool>,
    form: web::Form<LocationForm>,
) -> Result<impl Responder, ApplicationError> {
    if user.role == Role::AreaManager && user.role == Role::Admin {
        return Err(ApplicationError::Unauthorized);
    }

    let mut area_id = user.area_id;

    if user.role == Role::Admin && form.area.is_some() {
        area_id = form.area.unwrap();
    }

    // TODO: rework
    match Location::create(pool.get_ref(), &form.name, area_id).await {
        Ok(_) => {
            return Ok(HttpResponse::Found()
                .insert_header((LOCATION, "/locations"))
                .insert_header(("HX-LOCATION", "/locations"))
                .finish())
        }
        Err(err) => {
            println!("{}", err);
            return Ok(HttpResponse::InternalServerError().finish());
        }
    }
}
