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 guild_id = ctx.guild_id().ok_or("This command must be used in a server")?;
        let user_id = ctx.author().id;

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

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

        Ok(())
    }
}

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