use crate::{Context, Error};
use poise::serenity_prelude as serenity;

#[poise::command(slash_command, prefix_command, guild_only)]
pub async fn say(
    ctx: Context<'_>,
    #[description = "Message to say"] msg: String,
    #[description = "User to impersonate (optional)"] user: Option<serenity::User>,
) -> Result<(), Error> {
    let guild_id = ctx
        .guild_id()
        .ok_or_else(|| Error::msg("Guild only command"))?;

    if let poise::Context::Prefix(prefix_ctx) = ctx {
        let _ = prefix_ctx.msg.delete(ctx.http()).await;
    }

    let channel_id = ctx.channel_id();

    // Determine the user to impersonate (target user or author)
    let target_user = user.as_ref().unwrap_or_else(|| ctx.author());
    let username = if let Ok(member) = guild_id.member(ctx.http(), target_user.id).await {
        member.display_name().to_string()
    } else {
        target_user
            .global_name
            .as_ref()
            .unwrap_or(&target_user.name)
            .clone()
    };
    let avatar_url = target_user.face();

    // Find or create webhook
    let webhooks = ctx.http().get_channel_webhooks(channel_id).await?;
    let mut webhook = webhooks
        .into_iter()
        .find(|w| w.name.as_deref() == Some("void_sentinel"));

    if webhook.is_none() {
        let new_webhook = ctx
            .http()
            .create_webhook(
                channel_id,
                &serenity::CreateWebhook::new("void_sentinel"),
                None,
            )
            .await?;
        webhook = Some(new_webhook);
    }

    let webhook = webhook.unwrap();

    // Execute webhook
    let builder = serenity::ExecuteWebhook::new()
        .content(&msg)
        .username(username)
        .avatar_url(&avatar_url);

    webhook.execute(ctx.http(), false, builder).await?;

    // If it was a slash command, we might want to acknowledge it ephemerally so it doesn't fail
    if let poise::Context::Application(_) = ctx {
        // For slash command, send an ephemeral confirmation
        ctx.send(
            poise::CreateReply::default()
                .content("Message sent!")
                .ephemeral(true),
        )
        .await?;
    }

    Ok(())
}
