use crate::{
  chat::{edit_response, process_message},
  commands::audio::queue::pop_front,
  handler::get_songbird,
};
use serenity::{
  all::{CommandInteraction, CreateCommand, GuildId},
  prelude::*,
};
use songbird::Songbird;
use std::sync::Arc;

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;
    }
  };

  // Skip the track
  match skip_track(manager, guild_id).await {
    Ok(_) => {
      log::debug!("<{guild_id}> Skipped the track");
      edit_response(ctx, command, "Skipping the track".to_string()).await;
    }
    Err(err) => edit_response(ctx, command, format!("Failed to skip: {}", err)).await,
  }
}

pub async fn skip_track(manager: &Arc<Songbird>, guild_id: &GuildId) -> Result<(), String> {
  if let Some(handler_lock) = manager.get(guild_id.to_owned()) {
    let handler = handler_lock.lock().await;
    handler
      .queue()
      .skip()
      .map_err(|e| e.to_string())?;
    // Pop the current track from our metadata store; the next track (if any) moves to front
    pop_front(guild_id.get());
    Ok(())
  } else {
    Err("No active audio session in this guild".to_string())
  }
}

pub fn register() -> CreateCommand {
  CreateCommand::new("skip").description("Skip the current track")
}
