use serde::{Deserialize, Serialize};

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

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

impl Recordable for Options {
    async fn run(self, ctx: Context<'_>) -> Result<(), Error> {
        // ensure channel is cached
        ctx.channel_data().await?;

        sqlx::query!(
            "
            INSERT INTO todos (guild_id, channel_id, value)
            VALUES (
                (SELECT id FROM guilds WHERE guild = ?),
                (SELECT id FROM channels WHERE channel = ?),
                ?
            )
            ",
            ctx.guild_id().unwrap().get(),
            ctx.channel_id().get(),
            self.task
        )
        .execute(&ctx.data().database)
        .await
        .unwrap();

        ctx.say("Item added to todo list").await?;

        Ok(())
    }
}

/// Add an item to the channel todo list
#[poise::command(
    slash_command,
    rename = "add",
    guild_only = true,
    identifying_name = "todo_channel_add",
    default_member_permissions = "MANAGE_GUILD"
)]
pub async fn add(
    ctx: Context<'_>,
    #[description = "The task to add to the todo list"] task: String,
) -> Result<(), Error> {
    (Options { task }).run(ctx).await
}
