// Copyright (C) Call of Nil contributors
// SPDX-License-Identifier: AGPL-3.0-only

use crate::app::App;
use crate::res;
use axum::extract::{Json, State};
use axum::response::Response;
use itertools::Itertools;
use nil_core::npc::precursor::PublicPrecursor;
use nil_payload::request::npc::precursor::*;
use nil_payload::response::npc::precursor::*;

pub async fn get_coords(
  State(app): State<App>,
  Json(req): Json<GetPrecursorCoordsRequest>,
) -> Response {
  app
    .continent(req.world, |k| k.coords_of(req.id).collect_vec())
    .await
    .map_left(|coords| res!(OK, GetPrecursorCoordsResponse(coords)))
    .into_inner()
}

pub async fn get_public_precursor(
  State(app): State<App>,
  Json(req): Json<GetPublicPrecursorRequest>,
) -> Response {
  app
    .precursor_manager(req.world, |pm| PublicPrecursor::new(pm.precursor(req.id)))
    .await
    .map_left(|precursor| res!(OK, GetPublicPrecursorResponse(precursor)))
    .into_inner()
}

pub async fn get_public_precursors(
  State(app): State<App>,
  Json(req): Json<GetPublicPrecursorsRequest>,
) -> Response {
  app
    .precursor_manager(req.world, |pm| {
      pm.precursors()
        .map(PublicPrecursor::from)
        .collect_vec()
    })
    .await
    .map_left(|precursors| res!(OK, GetPublicPrecursorsResponse(precursors)))
    .into_inner()
}
