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

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

#[derive(Template)]
#[template(path = "vehicles/overview.html")]
pub struct VehiclesOverviewTemplate {
    user: User,
    vehicles: Vec<Vehicle>
}

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

    let vehicles = Vehicle::read_all(pool.get_ref()).await?;

    let template = VehiclesOverviewTemplate {
        user: user.into_inner(),
        vehicles
    };

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