use actix_web::{web, HttpResponse, Responder};
use rinja::Template;
use sqlx::PgPool;

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

#[actix_web::get("/vehicles/{id}")]
pub async fn get(
    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);
    }

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

    let template = VehicleNewOrEditTemplate {
        user: user.into_inner(),
        vehicle: Some(vehicle),
    };

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