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

use crate::{
    utils::{check_user_subscription, 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;

        // Check if user has Patreon subscription
        if !check_user_subscription(ctx, user_id).await {
            ctx.send(CreateReply::default()
                .content("❌ You must be a Patreon subscriber to use this command. Use `/patreon info` for more information.")
                .ephemeral(true)
            ).await?;
            return Ok(());
        }

        // Insert or update the patreon_link entry
        sqlx::query!(
            "INSERT INTO patreon_link (user_id, guild_id, linked_at) VALUES (?, ?, NOW())
             ON DUPLICATE KEY UPDATE guild_id = ?",
            user_id.get(),
            guild_id.get(),
            guild_id.get()
        )
        .execute(&ctx.data().database)
        .await?;

        ctx.send(
            CreateReply::default()
                .content("✅ Successfully linked your Patreon subscription to this server!")
                .ephemeral(true),
        )
        .await?;

        Ok(())
    }
}

/// Link your Patreon subscription to this server to allow other users Patreon access.
#[poise::command(
    slash_command,
    rename = "link",
    identifying_name = "patreon_link",
    guild_only = true
)]
pub async fn link(ctx: Context<'_>) -> Result<(), Error> {
    (Options {}).run(ctx).await
}
