locals {
  # Create a map of groups by dashboard_alert_group_name for parent lookup
  groups_by_name = {
    for group in var.groups : group.dashboard_alert_group_name => group
  }

  # Helper function to extract parent folder name and child folder name
  # If dashboard_alert_group_name contains "/", split it into parent and child
  folder_structure = {
    for group in var.groups : group.dashboard_alert_group_name => {
      group              = group
      parts              = split("/", group.dashboard_alert_group_name)
      has_parent         = length(split("/", group.dashboard_alert_group_name)) > 1
      parent_folder_name = length(split("/", group.dashboard_alert_group_name)) > 1 ? join("/", slice(split("/", group.dashboard_alert_group_name), 0, length(split("/", group.dashboard_alert_group_name)) - 1)) : null
      folder_title       = length(split("/", group.dashboard_alert_group_name)) > 1 ? element(split("/", group.dashboard_alert_group_name), length(split("/", group.dashboard_alert_group_name)) - 1) : group.dashboard_alert_group_name
      # Get parent folder UID from parent group's folder_uid
      parent_folder_uid = length(split("/", group.dashboard_alert_group_name)) > 1 ? try(local.groups_by_name[join("/", slice(split("/", group.dashboard_alert_group_name), 0, length(split("/", group.dashboard_alert_group_name)) - 1))].folder_uid, null) : null
    }
  }

  # Group folders by whether they should keep manual changes or be protected from destruction
  folders_ignore_only = {
    for group_name, folder_info in local.folder_structure : group_name => folder_info
    if lookup(folder_info.group, "keep_manual_changes", false) && !lookup(folder_info.group, "prevent_destroy_on_recreate", false)
  }

  folders_protect_only = {
    for group_name, folder_info in local.folder_structure : group_name => folder_info
    if !lookup(folder_info.group, "keep_manual_changes", false) && lookup(folder_info.group, "prevent_destroy_on_recreate", false)
  }

  folders_ignore_and_protect = {
    for group_name, folder_info in local.folder_structure : group_name => folder_info
    if lookup(folder_info.group, "keep_manual_changes", false) && lookup(folder_info.group, "prevent_destroy_on_recreate", false)
  }

  folders_standard = {
    for group_name, folder_info in local.folder_structure : group_name => folder_info
    if !lookup(folder_info.group, "keep_manual_changes", false) && !lookup(folder_info.group, "prevent_destroy_on_recreate", false)
  }

  # Create a map of all folders for parent UID lookup
  all_folders = merge(
    local.folders_ignore_and_protect,
    local.folders_ignore_only,
    local.folders_protect_only,
    local.folders_standard
  )
}
