import { world, Player, EntityComponentTypes } from "@minecraft/server";

world.afterEvents.entityHurt.subscribe((event) => {
  const { damage, damageSource, hurtEntity } = event;
  if (damage <= 0) return;

  const attacker = damageSource?.damagingEntity;
  if (!(attacker instanceof Player)) return;
  if (!attacker.hasTag("glimmerite_armor")) return;

  let multiplier = 0.95;

  try {
    const familyComp = hurtEntity.getComponent("minecraft:type_family");
    if (familyComp?.hasTypeFamily("monster")) {
      if (attacker.hasTag("difficulty_phase1")) {
        multiplier = 0.93;
      } else if (attacker.hasTag("difficulty_phase2")) {
        multiplier = 0.93;
      } else if (attacker.hasTag("difficulty_phase3")) {
        multiplier = 0.9;
      } else if (attacker.hasTag("difficulty_phase4")) {
        multiplier = 0.9;
      }
    }
  } catch {}

  const healAmount = damage * multiplier;
  healEntitySafe(hurtEntity, healAmount);
});

function healEntitySafe(entity, amount) {
  if (!entity || amount <= 0) return;

  try {
    const healthComp = entity.getComponent(EntityComponentTypes.Health);
    if (!healthComp) return;

    const current = healthComp.currentValue;
    const max = healthComp.effectiveMax;
    if (current <= 0 || current >= max) return;

    healthComp.setCurrentValue(
      Math.min(current + amount, max)
    );
  } catch {}
}
