#' Estimate time-to-breach survival model
#'
#' @param data A data frame from vowr_import().
#' @param threshold Mean waiting-time threshold in weeks. Default is 18.
#'
#' @return A list containing a Kaplan-Meier survival model object and the data
#' used to fit the model.
#'
#' @importFrom survival Surv survfit
#' @importFrom dplyr group_by summarise mutate filter left_join
#' @export
vowr_survival <- function(data, threshold = 18) {

  # Ensure period is in Date format
  data$period <- as.Date(data$period, format = "%d/%m/%Y")

  # 1. Identify first month of breach for each provider
  breach_data <- dplyr::filter(data, mean_wait_weeks > threshold)
  breach_data <- dplyr::group_by(breach_data, provider_org_code)
  breach_data <- dplyr::summarise(
    breach_data,
    first_breach = min(period, na.rm = TRUE),
    .groups = "drop"
  )

  # 2. Get start/end dates for each provider
  censoring_data <- dplyr::group_by(data, provider_org_code)
  censoring_data <- dplyr::summarise(
    censoring_data,
    start_date = min(period, na.rm = TRUE),
    end_date = max(period, na.rm = TRUE),
    .groups = "drop"
  )

  # 3. Join and create survival object
  surv_input <- dplyr::left_join(censoring_data, breach_data, by = "provider_org_code")
  surv_input <- dplyr::mutate(
    surv_input,
    status = ifelse(is.na(first_breach), 0, 1),
    time_days = ifelse(
      is.na(first_breach),
      as.numeric(end_date - start_date),
      as.numeric(first_breach - start_date)
    )
  )

  # 4. Fit survival model using Kaplan-Meier method
  surv_obj <- survival::Surv(time = surv_input$time_days, event = surv_input$status)
  fit <- survival::survfit(surv_obj ~ 1)

  return(list(fit = fit, surv_data = surv_input))
}
