use poise::CreateReply;
use serde::{Deserialize, Serialize};

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

#[derive(Serialize, Deserialize, Extract)]
pub struct Options;

impl Recordable for Options {
    async fn run(self, ctx: Context<'_>) -> Result<(), Error> {
        let user_id = ctx.author().id;

        // Remove the patreon_link entry
        let result = sqlx::query!("DELETE FROM patreon_link WHERE user_id = ?", user_id.get())
            .execute(&ctx.data().database)
            .await?;

        if result.rows_affected() > 0 {
            ctx.send(
                CreateReply::default()
                    .content("✅ Successfully unlinked your Patreon subscription!")
                    .ephemeral(true),
            )
            .await?;
        } else {
            ctx.send(
                CreateReply::default()
                    .content("❌ No existing Patreon link found.")
                    .ephemeral(true),
            )
            .await?;
        }

        Ok(())
    }
}

/// Unlink your Patreon subscription
#[poise::command(
    slash_command,
    rename = "unlink",
    identifying_name = "patreon_unlink",
    guild_only = false
)]
pub async fn unlink(ctx: Context<'_>) -> Result<(), Error> {
    (Options {}).run(ctx).await
}
