use serde::{Deserialize, Serialize};

use crate::{
    utils::{Extract, Recordable},
    Context, Error,
};

#[derive(Serialize, Deserialize, Extract)]
pub struct Options {
    name: String,
}

impl Recordable for Options {
    async fn run(self, ctx: Context<'_>) -> Result<(), Error> {
        let owner = ctx.guild_id().map(|g| g.get()).unwrap_or_else(|| ctx.author().id.get());

        let exists = sqlx::query!(
            "
            SELECT 1 as _r
            FROM timers
            WHERE owner = ?
                AND name = ?
            ",
            owner,
            self.name
        )
        .fetch_one(&ctx.data().database)
        .await;

        if exists.is_ok() {
            sqlx::query!(
                "
                DELETE FROM timers
                WHERE owner = ?
                    AND name = ?
                ",
                owner,
                self.name
            )
            .execute(&ctx.data().database)
            .await
            .unwrap();

            ctx.say("Deleted a timer").await?;
        } else {
            ctx.say("Could not find a timer by that name").await?;
        }

        Ok(())
    }
}

/// Delete a timer
#[poise::command(
    slash_command,
    rename = "delete",
    identifying_name = "delete_timer",
    default_member_permissions = "MANAGE_GUILD"
)]
pub async fn delete(
    ctx: Context<'_>,
    #[description = "Name of timer to delete"] name: String,
) -> Result<(), Error> {
    (Options { name }).run(ctx).await
}
