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

#' Collective treatment cost calculation
#' 
#' Calculate cost of the simulated collective treatment train
#' @param scenario data.frame scenario with irrigation_need_m3an column obtained with irrigation_need_calculation
#' @param grant numeric amount of the grant in percentage 
#' @param allocation_key data.frame allocation key, NULL by default
#' @importFrom dplyr mutate filter
#' @return cost
#' 
#' @export
#' @examples
#' scenario_apprentissage <- create_scenario(
#'   system.file("input_1culture_2pop.xlsx", package = "ambre")
#' )
#' irrigation_need <- irrigation_need_calculation(scenario_apprentissage)
#' collective_treatment_cost_calculation(scenario = irrigation_need, 
#'                                       grant = 0.5)
#'
#' crop <- scenario_apprentissage$CropName |> unique()
#' allocation_custom <- data.frame(CropName = crop,
#'                                 allocation = c(0.5, 0.1, 0.1, 0.1, 0.1, 0.1))
#' collective_treatment_cost_calculation(scenario = irrigation_need, 
#'                                       grant = 0,
#'                                       allocation_key = allocation_custom)
collective_treatment_cost_calculation <- function(
  scenario,
  grant,
  allocation_key = NULL
){
  collective_ids <- unique(
    stats::na.omit(
      unlist(
        scenario$CollectiveTreatmentID,
        use.names = FALSE
      )
    )
  )
  if (length(collective_ids) == 0) {
    stop("No collective treatement defined in the scenario simulated")
  }

  if (!is.null(allocation_key)) {
    if (!is.data.frame(allocation_key)) {
      stop("'allocation_key' must be a data.frame.")
    }

    required_cols <- c("CropName", "allocation")
    missing_cols <- setdiff(required_cols, names(allocation_key))

    if (length(missing_cols) > 0) {
      stop(
        "'allocation_key' must contain the following columns: ",
        paste(required_cols, collapse = ", "),
        ". Missing: ",
        paste(missing_cols, collapse = ", ")
      )
    }
  }

  capex_cost <- filter(
    config_ambre$economic$cost,
    TreatmentID %in% collective_ids
  ) |>
    filter(CostType == "capex")

  opex_cost <- filter(
    config_ambre$economic$cost,
    TreatmentID %in% collective_ids
  ) |>
    filter(CostType == "opex")


  cost <- data.frame(
      volume_to_treat = total_irrigation_need(scenario),
      capex = sum(
        capex_cost$value,
        na.rm = TRUE
      ),
      opex = sum(
        opex_cost$value,
        na.rm = TRUE
      )
    ) |>
      mutate(
        investissement = capex * volume_to_treat
      ) |>
      mutate(
        operation_cost = opex * volume_to_treat
  )

  scenario_updated <- scenario
  scenario_updated$collective_opex <- cost$opex * scenario_updated$irrigation_need_m3an
  
# CAPEX
  total_area <- total_area_calculation(scenario = scenario_updated)
  capex_ttt_collectif <- cost$investissement
  
  if (is.null(allocation_key)){
    scenario_updated <- scenario_updated |>
                      mutate("allocation" = round((1 - grant) * Area / total_area, 4))
  } else {
    scenario_updated <- scenario_updated |>
      left_join(allocation_key, by = "CropName")
  }
  
  
  scenario_updated <- scenario_updated |>
                      mutate("capex_collective_treatment" = round(allocation * capex_ttt_collectif, 0)) |>
                      mutate("loan_asa" = capex_collective_treatment/(20*Area)) |>
  mutate(loan_asa = round(loan_asa*Area, 0))
  
  allocation_key <- data.frame(grant = grant,
                               CropName = scenario_updated$CropName,
                               allocation = scenario_updated$allocation) |>
    unique()
  
  result <- list(scenario = scenario_updated,
                 allocation_key = allocation_key)
  
  return(result)
    
}
