use rocket::{http::Status, serde::json::Json};

use crate::{model::register::{Register, RegisterCreate}, json_result::JsonResult};

#[options("/register/batch")]
pub fn options() -> Status {
    Status::Ok
}

#[options("/register/<_r>")]
pub fn options_delete(_r: i32) -> Status {
    Status::Ok
}

#[post("/register/batch", format = "json", data = "<data>")]
pub async fn insert_all(data: Json<Vec<RegisterCreate>>) -> Status {
    for register_create in data.iter() {
        let res = register_create.create().await;

        if let Err(err) = res {
            eprintln!("Error creating register: {}", err);
            return Status::InternalServerError;
        }
    }

    Status::Ok
}

#[get("/register/<dni>")]
pub async fn get_by_dni(dni: i32) -> (Status, Json<JsonResult<Vec<Register>>>) {
    let registers = Register::get_by_dni(dni).await;

    match registers {
        Ok(data) => (Status::Ok, JsonResult::ok(data)),
        Err(err) => {
            eprintln!("{:?}", err);

            (Status::InternalServerError, JsonResult::err(format!("Error recuperando certs de DB")))
        }
    }
}

#[delete("/register/<register_id>")]
pub async fn delete(register_id: i32) -> Status {
    let res = Register::delete(register_id).await;

    match res {
        Ok(_) => Status::Ok,
        Err(err) => {
            eprintln!("{:?}", err);

            Status::InternalServerError
        }
    }
}
