using GameDev.CoreSystems;
using UnityEngine;

namespace AsteroidGame.Entities
{
    public class EntityBase : MonoBehaviour
    {
        [field: Header("Damageable")]
        [field: SerializeField] public Damageable Damageable { get; set; }

        [field: Header("Targetable")]
        [field: SerializeField] public Targetable Targetable { get; set; }

        [Header("UI")]
        [SerializeField] protected string _uiFriendlyName;

        #region Props

        public string UiFriendlyName => _uiFriendlyName;

        #endregion

        private void Awake()
        {
            InitializeDamageable();

            InitializeTargetable();

            AssignDamageable();
        }

        private void InitializeDamageable()
        {
            Damageable ??= gameObject.AddComponent<Damageable>();
            Damageable.DeathEvent.AddListener(HandleDeath);
        }

        private void HandleDeath()
        {
            Destroy(gameObject);
        }

        private void InitializeTargetable()
        {
            Targetable ??= gameObject.AddComponent<Targetable>();
        }

        private void AssignDamageable()
        {
            if (Targetable.Damageable != null) return;

            Targetable.Damageable = Damageable;
        }
    }
}