use log::error;
use rocket::{
    http::CookieJar,
    post,
    serde::{
        json::{json, Json},
        Deserialize,
    },
};

use crate::web::routes::JsonResult;

#[derive(Deserialize)]
pub struct ClientError {
    #[serde(rename = "reporterId")]
    reporter_id: String,
    url: String,
    #[serde(rename = "relativeTimestamp")]
    relative_timestamp: i64,
    #[serde(rename = "errorMessage")]
    error_message: String,
    #[serde(rename = "errorLine")]
    error_line: u64,
    #[serde(rename = "errorFile")]
    error_file: String,
    #[serde(rename = "errorType")]
    error_type: String,
}

#[post("/report", data = "<client_error>")]
pub async fn report_error(cookies: &CookieJar<'_>, client_error: Json<ClientError>) -> JsonResult {
    if let Some(user_id) = cookies.get_private("userid") {
        error!(
            "User {} reports a client-side error.
{}, {}:{} at {}ms
{}: {}
Chain: {}",
            user_id,
            client_error.url,
            client_error.error_file,
            client_error.error_line,
            client_error.relative_timestamp,
            client_error.error_type,
            client_error.error_message,
            client_error.reporter_id
        );
    }

    Ok(json!({}))
}
