use crate::{Context, Error};

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
struct BetaInfo {
    guild_id: String,
    added_at: chrono::DateTime<chrono::Utc>,
    added_by: String,
}

/// Add a server to beta testing (Owner only)
#[poise::command(slash_command, prefix_command, owners_only)]
pub async fn add_beta_testing(
    ctx: Context<'_>,
    #[description = "The server ID to add (defaults to current server)"] server_id: Option<String>,
) -> Result<(), Error> {
    let guild_id = if let Some(id) = server_id {
        id
    } else if let Some(id) = ctx.guild_id() {
        id.to_string()
    } else {
        ctx.say("Please provide a server ID or run this command in a server.").await?;
        return Ok(());
    };

    let db = &ctx.data().db;
    
    let beta_info = BetaInfo {
        guild_id: guild_id.clone(),
        added_at: chrono::Utc::now(),
        added_by: ctx.author().id.to_string(),
    };

    let _: Option<BetaInfo> = db
        .create(("beta_testing", &guild_id))
        .content(beta_info)
        .await?;

    ctx.say(format!("Added server {} to beta testing.", guild_id)).await?;

    Ok(())
}

/// List all beta testing servers (Owner only)
#[poise::command(slash_command, prefix_command, owners_only)]
pub async fn list_beta_testing(ctx: Context<'_>) -> Result<(), Error> {
    let db = &ctx.data().db;

    let servers: Vec<BetaInfo> = db.select("beta_testing").await?;

    if servers.is_empty() {
        ctx.say("No servers in beta testing.").await?;
        return Ok(());
    }

    let mut response = String::from("**Beta Testing Servers:**\n");
    for server in servers {
        response.push_str(&format!("- {} (Added: <t:{}:R>)\n", server.guild_id, server.added_at.timestamp()));
    }

    ctx.say(response).await?;

    Ok(())
}

/// Remove a server from beta testing (Owner only)
#[poise::command(slash_command, prefix_command, owners_only)]
pub async fn remove_beta_testing(
    ctx: Context<'_>,
    #[description = "The server ID to remove (defaults to current server)"] server_id: Option<String>,
) -> Result<(), Error> {
    let guild_id = if let Some(id) = server_id {
        id
    } else if let Some(id) = ctx.guild_id() {
        id.to_string()
    } else {
        ctx.say("Please provide a server ID or run this command in a server.").await?;
        return Ok(());
    };

    let db = &ctx.data().db;

    let _: Option<BetaInfo> = db.delete(("beta_testing", &guild_id)).await?;

    ctx.say(format!("Removed server {} from beta testing.", guild_id)).await?;

    Ok(())
}
