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

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

#[derive(Template)]
#[template(path = "location/overview.html")]
pub struct LocationsTemplate {
    user: User,
    grouped_locations: Vec<(Area, Vec<Location>)>,
}

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

    let mut locations;
    let mut grouped_locations: Vec<(Area, Vec<Location>)>;

    if user.role == Role::Admin {
        locations = Location::read_all(pool.get_ref()).await.unwrap();
        grouped_locations = Area::read_all(pool.get_ref())
            .await?
            .into_iter()
            .map(|a| (a, Vec::new()))
            .collect();
    } else {
        locations = Location::read_by_area(pool.get_ref(), user.area_id).await?;
        let area = Area::read_by_id(pool.get_ref(), user.area_id)
            .await?
            .unwrap();

        grouped_locations = vec![(area, Vec::new())];
    }

    for entry in grouped_locations.iter_mut() {
        let (mut locations_in_this_area, rest): (Vec<_>, Vec<_>) =
            locations.into_iter().partition(|l| l.area_id == entry.0.id);
        locations = rest;

        entry.1.append(&mut locations_in_this_area);
    }

    let template = LocationsTemplate {
        user: user.into_inner(),
        grouped_locations,
    };

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