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

use crate::{
    endpoints::vehicle::VehicleForm,
    models::{Role, User, Vehicle},
    utils::ApplicationError,
};

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

    Vehicle::create(pool.get_ref(), &form.radio_call_name, &form.station).await?;

    Ok(HttpResponse::Found()
        .insert_header((LOCATION, "/vehicles"))
        .insert_header(("HX-LOCATION", "/vehicles"))
        .finish())
}
