extends Node

func _ready() -> void:
  EventBus.damage_requested.connect(_on_damage_requested)

func _on_damage_requested(attacker: Node, target: Node, amount: float) -> void:
  var remaining: float = amount
  if not target.is_in_group("tavern"):
    var shield_system: Node = get_node_or_null("../ShieldSystem")
    if shield_system:
      remaining = shield_system.absorb(target, remaining)
  EventBus.damage_dealt.emit(attacker, target, amount)
  if remaining > 0:
    _apply_damage(target, remaining)

func _apply_damage(entity: Node, amount: float) -> void:
  if entity == _get_player():
    var health: float = PlayerData.health - amount
    if health < 0:
      health = 0
    PlayerData.set_health(health)
  elif entity.is_in_group("boss"):
    var health: float = BossData.get_stat(entity, "health") - amount
    if health < 0:
      health = 0
    BossData.set_health(entity, health)
  elif entity.is_in_group("enemies"):
    var health: float = EnemyData.get_stat(entity, "health") - amount
    if health < 0:
      health = 0
    EnemyData.set_health(entity, health)
  elif entity.is_in_group("portals"):
    var health: float = PortalData.get_stat(entity, "health") - amount
    if health < 0:
      health = 0
    PortalData.set_health(entity, health)
  elif entity.is_in_group("tavern"):
    var health: float = TavernData.get_stat(entity, "health") - amount
    if health < 0:
      health = 0
    TavernData.set_health(entity, health)

func _get_player() -> Node:
  return get_tree().get_first_node_in_group("player")
