#' Wilcoxon-Mann-Whitney U-Test for Differential Gene Expression
#'
#' Performs the Wilcoxon rank-sum (Mann-Whitney U) test for every gene (row)
#' in the expression matrix, applies BH correction, and returns a results
#' table together with the list of significant DEGs.
#'
#' @inheritParams perform_t_test
#'
#' @return A named list:
#'   \describe{
#'     \item{Table}{Data.frame with columns \code{G_Symbol}, \code{log2FC},
#'       \code{statistic.W}, \code{p.value}, \code{BH}, \code{fdr}.}
#'     \item{DEGs}{Data.frame of significant gene identifiers.}
#'   }
#'
#' @export
#' @importFrom stats wilcox.test p.adjust na.omit quantile
#' @examples
#' library(DGEAR)
#' data("gene_exp_data")
#' result <- perform_wilcox_test(dataframe = gene_exp_data,
#'                               con1 = 1, con2 = 10,
#'                               exp1 = 11, exp2 = 20)
#' head(result$Table)
#' result$DEGs
perform_wilcox_test <- function(dataframe, con1, con2, exp1, exp2,
                                alpha = 0.05, annot_df = NULL) {
  prep     <- .prepare_data(dataframe, con1, con2, exp1, exp2)
  G_Symbol <- .resolve_symbols(prep$dataframe, annot_df)
  con      <- prep$con
  exp      <- prep$exp
  log2FC   <- prep$log2FC
  
  u_results <- t(sapply(seq_len(nrow(con)), function(i) {
    res <- suppressWarnings(
      wilcox.test(as.numeric(con[i, ]), as.numeric(exp[i, ]), paired = FALSE)
    )
    c(statistic.W = res$statistic, p.value = res$p.value)
  }))
  
  u_stat         <- data.frame(G_Symbol, log2FC, u_results,
                               stringsAsFactors = FALSE)
  u_stat$BH      <- p.adjust(u_stat$p.value, method = "BH")
  u_stat$fdr     <- as.integer(u_stat$BH <= alpha)
  
  DEGs <- data.frame(DEGs = na.omit(u_stat$G_Symbol[u_stat$fdr == 1L]),
                     stringsAsFactors = FALSE)
  list(Table = u_stat, DEGs = DEGs)
}
