use poise::{serenity_prelude::CreateEmbed, CreateReply};

use crate::{consts::THEME_COLOR, Context, Error};

/// Finish current macro recording
#[poise::command(
    slash_command,
    rename = "finish",
    guild_only = true,
    default_member_permissions = "MANAGE_GUILD",
    identifying_name = "finish_macro"
)]
pub async fn finish_macro(ctx: Context<'_>) -> Result<(), Error> {
    let key = (ctx.guild_id().unwrap(), ctx.author().id);

    {
        let lock = ctx.data().recording_macros.read().await;
        let contained = lock.get(&key);

        if contained.map_or(true, |r#macro| r#macro.commands.is_empty()) {
            ctx.send(
                CreateReply::default().embed(
                    CreateEmbed::new()
                        .title("No Macro Recorded")
                        .description("Use `/macro record` to start recording a macro")
                        .color(*THEME_COLOR),
                ),
            )
            .await?;
        } else {
            let command_macro = contained.unwrap();
            let json = serde_json::to_string(&command_macro.commands).unwrap();

            sqlx::query!(
                "INSERT INTO command_macro (guild_id, name, description, commands) VALUES ((SELECT id FROM guilds WHERE guild = ?), ?, ?, ?)",
                command_macro.guild_id.get(),
                command_macro.name,
                command_macro.description,
                json
            )
                .execute(&ctx.data().database)
                .await
                .unwrap();

            ctx.send(
                CreateReply::default().embed(
                    CreateEmbed::new()
                        .title("Macro Recorded")
                        .description("Use `/macro run` to execute the macro")
                        .color(*THEME_COLOR),
                ),
            )
            .await?;
        }
    }

    {
        let mut lock = ctx.data().recording_macros.write().await;
        lock.remove(&key);
    }

    Ok(())
}
