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

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

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

    let Some(vehicle) = Vehicle::read(pool.get_ref(), path.id).await? else {
        return Ok(HttpResponse::NotFound().finish());
    };

    if vehicle.radio_call_name != form.radio_call_name || vehicle.station != form.station {
        Vehicle::update(
            pool.get_ref(),
            path.id,
            &form.radio_call_name,
            &form.station,
        )
        .await?;
    }

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