# WARNING - Generated by {fusen} from dev/flat_qmra.Rmd: do not edit by hand # nolint: line_length_linter.

#' Final dose calculation
#' 
#' Calculation of the final dose according to initial dose and log reduction of the treatments simulated
#' @param scenario dataFrame scenario with initial_dose and log_reduction columns
#' @importFrom purrr map2 map
#' @importFrom dplyr mutate group_by summarise
#' @return scenario_with_final_dose
#' 
#' @export
#' @examples
#' library(dplyr)
#' library(purrr)
#' scenario_test <- create_scenario(system.file("input_1culture_2pop.xlsx", package = "ambre"))
#'
#' scenario_conc <- inflow_concentration(scenario = scenario_test,
#'  pathogenName = c("Campylobacter jejuni", "Escherichia coli"))
#'
#' scenario_volume <-
#'   scenario_conc |>                     
#'   mutate(
#'     volume = map(
#'       .x = config,                                         
#'       .f = ~ simulate_exposure(config = .x)              
#'     )
#'   )
#'
#' scenario_dose_ini <- initial_dose_calculation(scenario_volume)
#'
#' scenario_scheme <- update_treatment_scheme(scenario_dose_ini)
#'
#' scenario_with_logreduc_and_co <- scenario_scheme |> 
#'   mutate( log_reduction = map(config, simulate_treatment))
#'
#' final_dose_calculation(scenario_with_logreduc_and_co)
final_dose_calculation <- function(scenario){
  if (!"initial_dose" %in% names(scenario)) {
  stop("The initial_dose column is missing from the scenario object; run the initial_dose_calculation function to create it")
}
  
  if (!"log_reduction" %in% names(scenario)) {
  stop("The log_reduction column is missing from the scenario object; run the simulate_treatment function to create it")
  }
  
  total_logreduction <- map(
  scenario$log_reduction,
  ~ .x$events_long |>
      group_by(repeatID, eventID, PathogenGroup) |>
      summarise(total_logreduction = sum(logreduction), .groups = "drop")
)
  
  scenario_total_logreduction <- scenario |> mutate(total_logreduction = total_logreduction)

  
  ppp <- map2(.x = scenario$inflow_concentration, 
              .y = scenario$volume,
              .f = ~dplyr::left_join(.x$events, .y$volumes$events, by = c("repeatID", "eventID")))
  
  
  ccc <- map2(.x= ppp, 
              .y = total_logreduction, 
              .f= ~left_join(.x, .y, by = c("repeatID", "eventID", "PathogenGroup")))
  
  
  final_dose <- map(.x = ccc , ~{
    .x$final_dose <- (.x$inflow * .x$volume_perEvent)*10^(-.x$total_logreduction)
    .x
  })
  
  scenario_with_final_dose <- scenario_total_logreduction |> mutate(
    final_dose = final_dose)
  
  return(scenario_with_final_dose)
}
