using UnityEngine;

public class AreaEffect : MonoBehaviour, ISkillEffect
{
    public void Execute(SkillInstance skill, Transform caster, float chargeRatio)
    {
        Vector3 center = caster.position + caster.forward * skill.CurrentLevelData.Range;
        ApplyArea(skill, caster, center, chargeRatio);
    }

    public void ExecuteAtPosition(SkillInstance skill, Transform caster, Vector3 targetPos, float chargeRatio)
    {
        ApplyArea(skill, caster, targetPos, chargeRatio);
    }

    private void ApplyArea(SkillInstance skill, Transform caster, Vector3 center, float chargeRatio)
    {
        SkillLevelData levelData = skill.CurrentLevelData;
        int damage = Mathf.RoundToInt(levelData.Damage * chargeRatio);

        if (skill.Data.AttackEffectPrefab != null)
        {
            Instantiate(skill.Data.AttackEffectPrefab, center, Quaternion.identity);
        }

        Collider[] hits = Physics.OverlapSphere(center, levelData.Range);
        foreach (Collider hit in hits)
        {
            if (hit.transform == caster) continue;

            IDamageable target = hit.GetComponent<IDamageable>();
            if (target != null)
            {
                target.TakeDamage(damage, caster);

                if (skill.Data.AppliedDebuffs != null)
                {
                    StatusEffectReceiver receiver = hit.GetComponent<StatusEffectReceiver>();
                    if (receiver != null)
                    {
                        foreach (var debuff in skill.Data.AppliedDebuffs)
                            receiver.ApplyDebuff(debuff);
                    }
                }
            }
        }
    }
}
