#' Drop and merge replicated columns from the specified data frame.
#' 
#' This function drops and merges all the replicated columns from the specified
#' data frame.
#'
#' @param dataframe `data.frame`. The data frame from which to drop the
#'   replicated columns.
#' 
#' @param prefix `character` (string). The prefix with which the name of the
#'   replicated columns starts.
#' 
#' @returns The specified data frame with an additional deduplicated column and
#'   all the types transformed to string.
#'
#' @importFrom dplyr mutate across starts_with select bind_cols na_if any_of
#' @importFrom tidyr unite
#' @importFrom stringr str_replace_all regex
#' @importFrom glue glue
#' @importFrom checkmate assert_data_frame assert_string
#' @importFrom rlang := sym
#' 
#' @details
#' All the occurrences of "N/A", "NA", and empty strings (case insensitive)
#' inside the provided data frame are replaced with NAs of type character.
#' Then, all and only the columns starting with the specified prefix are
#' selected and united into a single column with name ending per
#' "_deduplicated". All empty entries in the new deduplicated column are
#' replaced with NAs. Finally, the new column is bound with the other columns of
#' the initial dataframe.
#'
#' @examples
#' irisTest_ <- iris
#' irisTest_$Species_1 <- irisTest_$Species
#' irisTest_$Species_2 <- irisTest_$Species
#' irisTest_$Species <- NULL
#' 
#' deduplicatedDataframe_ <- removeReplicatedColumns(
#'   dataframe = irisTest_,
#'   prefix = "Species_")
#'
#' @export
#'
removeReplicatedColumns <- function(dataframe, prefix) {

  assert_data_frame(dataframe)
  assert_string(prefix)

  dataframe <- dataframe |>
    
    mutate(across(starts_with(prefix), as.character)) |>
    
    mutate(across(starts_with(prefix),
      \(x) str_replace_all(
        x,
        regex("^N/a$|^Na$|^$", ignore_case = TRUE),
        NA_character_)))

  dataframe_prefix_columns_ <- dataframe |>
    select(starts_with(prefix))

  dataframe_prefix_columns_ <- dataframe_prefix_columns_ |>
    
    unite(!!glue("{prefix}_deduplicated"),
      1:ncol(dataframe_prefix_columns_),
      sep = "",
      na.rm = TRUE) |>
    
    mutate(!!glue("{prefix}_deduplicated")
      := na_if(!!sym(glue("{prefix}_deduplicated")), "")) |>
    
    bind_cols(
      dataframe |>
      select(-starts_with(prefix)) |>
      select(any_of(names(dataframe)))) |>
    
    mutate_all(as.character)

  return(dataframe_prefix_columns_)
}
