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

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

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

impl Recordable for Options {
    async fn run(self, ctx: Context<'_>) -> Result<(), Error> {
        match ctx.channel_data().await {
            Ok(data) => {
                if let (Some(id), Some(token)) = (data.webhook_id, data.webhook_token) {
                    ctx.send(CreateReply::default().ephemeral(true).content(format!(
                        "**Warning!**
This link can be used by users to anonymously send messages, with or without permissions.
Do not share it!
|| https://discord.com/api/webhooks/{}/{} ||",
                        id, token,
                    )))
                    .await?;
                } else {
                    ctx.say("No webhook configured on this channel.").await?;
                }
            }
            Err(e) => {
                warn!("Error fetching channel data: {:?}", e);

                ctx.say("No webhook configured on this channel.").await?;
            }
        }

        Ok(())
    }
}

/// View the webhook being used to send reminders to this channel
#[poise::command(
    slash_command,
    rename = "webhook",
    identifying_name = "webhook",
    required_permissions = "ADMINISTRATOR"
)]
pub async fn command(ctx: Context<'_>) -> Result<(), Error> {
    (Options {}).run(ctx).await
}
