pub mod guild;
pub mod user;

use log::warn;
use rocket::{
    delete,
    http::CookieJar,
    serde::json::{json, Json},
    State,
};
use sqlx::{MySql, Pool};

use crate::web::routes::{dashboard::DeleteReminder, JsonResult};

#[delete("/api/reminders", data = "<reminder>")]
pub async fn delete_reminder(
    cookies: &CookieJar<'_>,
    reminder: Json<DeleteReminder>,
    pool: &State<Pool<MySql>>,
) -> JsonResult {
    match cookies.get_private("userid").map(|c| c.value().parse::<u64>().ok()).flatten() {
        Some(_) => {
            match sqlx::query!(
                "UPDATE reminders SET `status` = 'deleted' WHERE uid = ?",
                reminder.uid
            )
            .execute(pool.inner())
            .await
            {
                Ok(_) => Ok(json!({})),

                Err(e) => {
                    warn!("Error in `delete_reminder`: {:?}", e);

                    Err(json!({"error": "Could not delete reminder"}))
                }
            }
        }

        None => Err(json!({"error": "User not authorized"})),
    }
}
