use crate::{
  chat::{edit_response, process_message},
  handler::get_songbird,
};
use serenity::{
  all::{CommandInteraction, CreateCommand},
  prelude::*,
};

pub async fn run(ctx: &Context, command: &CommandInteraction) {
  // Create the initial response
  process_message(ctx, command, false).await;

  // Get the songbird manager
  let manager = get_songbird();

  // Extract the guild ID
  let guild_id = match &command.guild_id {
    Some(guild_id) => guild_id,
    None => {
      edit_response(
        ctx,
        command,
        "Unable to find the current server ID".to_string(),
      )
      .await;
      return;
    }
  };

  // Mute the track
  if let Some(handler_lock) = manager.get(guild_id.to_owned()) {
    let mut handler = handler_lock.lock().await;
    let is_muted = handler.is_mute();
    match handler.mute(!is_muted).await {
      Ok(_) => {
        if is_muted {
          log::debug!("<{guild_id}> Unmuted");
          edit_response(ctx, command, "Unmuted".to_string()).await;
        } else {
          log::debug!("<{guild_id}> Muted");
          edit_response(ctx, command, "Muted".to_string()).await;
        }
      }
      Err(err) => {
        edit_response(ctx, command, format!("Failed to mute: {}", err)).await;
      }
    }
  }
}

pub fn register() -> CreateCommand {
  CreateCommand::new("mute").description("Mute/unmute Siren")
}
