use gloo::net::http::Request;
use terminwahl_typen::{Nutzer, PlannedAppointment, RequestState};

use crate::Msg;

pub async fn fetch_teachers() -> Result<Msg, Msg> {
    // Send the request to the specified URL.
    let response = Request::get("/get/teachers/1").send().await;
    // Return the ZuordnungMessage with the given network object and the response.
    let response = response
        .map_err(|_| Msg::AppointmentsSent(RequestState::Error))?
        .json()
        .await
        .map_err(|_| Msg::AppointmentsSent(RequestState::Error))?;
    Ok(Msg::ReceivedTeachers(response))
}

pub async fn fetch_slots() -> Result<Msg, Msg> {
    // Send the request to the specified URL.
    let response = Request::get("/get/slots/1").send().await;
    // Return the ZuordnungMessage with the given network object and the response.
    let response = response
        .map_err(|_| Msg::AppointmentsSent(RequestState::Error))?
        .json()
        .await
        .map_err(|_| Msg::AppointmentsSent(RequestState::Error))?;
    Ok(Msg::ReceivedSlots(response))
}

pub async fn fetch_unavailable() -> Result<Msg, Msg> {
    // Send the request to the specified URL.
    let response = Request::get("/get/unavailable").send().await;
    // Return the ZuordnungMessage with the given network object and the response.
    let response = response
        .map_err(|_| Msg::AppointmentsSent(RequestState::Error))?
        .json()
        .await
        .map_err(|_| Msg::AppointmentsSent(RequestState::Error))?;
    Ok(Msg::ReceivedUnavailable(response))
}

pub async fn send_appointments(
    appointments: Vec<PlannedAppointment>,
    nutzer: Nutzer,
) -> Result<Msg, Msg> {
    let response = Request::post("/send/appointments")
        .json(&(&appointments, &nutzer))
        .map_err(|_| Msg::AppointmentsSent(RequestState::Error))?
        .send()
        .await;
    let response = response
        .map_err(|_| Msg::AppointmentsSent(RequestState::Error))?
        .json()
        .await
        .map_err(|_| Msg::AppointmentsSent(RequestState::Error))?;
    Ok(Msg::AppointmentsSent(response))
}