import { EntityProjectileComponent } from "@minecraft/server";
import { Server } from "../../../libs/Core/index.js";

const recentlyHurt = new Map();

Server.scriptEventManager.registerEvent('warden_sword_projectile_hit', (e) => {
    const projectile = e.sourceEntity;
    if (!projectile || !projectile.isValid()) return;

    /** @type {EntityProjectileComponent} */
    const projectileComponent = projectile.getComponent('minecraft:projectile');
    const owner = projectileComponent.owner;

    projectile.dimension.getEntities({
        tags: ['plank_waao:warden_sword_projectile_target'],
        maxDistance: 5,
        location: projectile.location
    }).forEach((m) => {
        m.removeTag('plank_waao:warden_sword_projectile_target');

        if (owner && m === owner) return;
        if (recentlyHurt.has(m)) {
            const lastHurt = recentlyHurt.get(m);
            if (Date.now() - lastHurt < 1000) return;
        }

        recentlyHurt.set(m, Date.now());
        if (recentlyHurt.size > 30) {
            const keys = Array.from(recentlyHurt.keys());
            for (let i = 0; i < 20; i++) {
                recentlyHurt.delete(keys[i]);
            }
        }

        m.applyDamage(15);
    });
});