#' Preparation des donnees de production renouvelable
#'
#' @param dataset le dataset prod-region-annuelle-enr telecharge sur ODRE 
#' @param region le code region, au format texte
#'
#' @return un dataframe contenant les donnees preparees et centrees sur la region observee
#' @importFrom rlang .data
#' @importFrom dplyr select mutate left_join group_by summarise across filter bind_rows if_else
#' @importFrom tidyr contains replace_na pivot_longer
#' @importFrom tidyselect vars_select_helpers
#' @export
#'
#' @examples
#' \dontrun{
#' prep_prod(dataset = prod_enr$dataset, region = "52")
#' }

prep_prod <- function(dataset, region = "52") {
  
  prod_enr_df <- dataset %>%
    dplyr::select(-tidyr::contains("geo_")) %>%
    dplyr::mutate(code_insee_region = as.character(.data$code_insee_region)) %>% 
    dplyr::left_join(bilan.eco.insee::regions, by = c("code_insee_region" = "REG"))
  
  prod_enr_df_Fce_metrop <- prod_enr_df %>% 
    dplyr::group_by(.data$annee) %>% 
    dplyr::summarise(dplyr::across(tidyselect::vars_select_helpers$where(is.numeric), sum, na.rm = TRUE)) %>% 
    dplyr::mutate(zone = "France")
  
  prod_enr_reg <- dplyr::filter(prod_enr_df, .data$code_insee_region == region) %>% 
    tidyr::replace_na(list(production_gaz_renouvelable = 0))
  
  prod_enr_viz <- prod_enr_reg %>% 
    dplyr::bind_rows(prod_enr_df_Fce_metrop) %>% 
    dplyr::select(-"code_insee_region", -"nom_insee_region") %>% 
    tidyr::pivot_longer(-c("annee", "zone"), names_to ="indicateur", values_to= "prod_TWh") %>% 
    dplyr::left_join(bilan.eco.insee::filieres, by = "indicateur" ) %>% 
    dplyr::mutate(
      indicateur = factor(.data$indicateur, levels = levels(bilan.eco.insee::filieres$indicateur)),
      prod_TWh = .data$prod_TWh/1000,
      region = dplyr::if_else(.data$zone == "France", "2FR", "1reg")
    ) 
  
  return(prod_enr_viz)
}
