// Assets/_Project/Scripts/Gameplay/Draft/NewTowerDraftOption.cs
using UnityEngine;
using TD.Towers;

namespace TD.Gameplay.Draft
{
    /// <summary>
    /// Draft choice #1 — "add a new tower to your arsenal". Grants the player a tower,
    /// adding it to their <see cref="PlayerTowerDeck"/>.
    /// </summary>
    /// <remarks>
    /// Only offered when the tower is in the match catalog AND the player doesn't already
    /// own it, so the draft never wastes a slot on a no-op.
    /// </remarks>
    [CreateAssetMenu(fileName = "NewTowerOption", menuName = "TD/Draft/New Tower Option")]
    public class NewTowerDraftOption : DraftOption
    {
        [Header("Payload")]
        [Tooltip("The tower this option grants. Must also be present in the " +
                 "TowerPlacementManager catalog (that's where its TowerTypeId comes from).")]
        public TowerDefinition Tower;

        public override bool IsValidFor(ulong clientId)
        {
            var deck = PlayerTowerDeck.GetForClient(clientId);
            var pm   = TowerPlacementManager.Instance;
            if (deck == null || pm == null || Tower == null) return false;

            // Not in the catalog → no TypeId → can't be granted or placed.
            if (!pm.TryGetTypeId(Tower, out int typeId)) return false;

            // Only offer towers the player hasn't unlocked yet.
            return !deck.Contains(typeId);
        }

        public override bool ServerApply(ulong clientId)
        {
            var deck = PlayerTowerDeck.GetForClient(clientId);
            var pm   = TowerPlacementManager.Instance;
            if (deck == null || pm == null || Tower == null) return false;

            if (!pm.TryGetTypeId(Tower, out int typeId))
            {
                Debug.LogError($"[NewTowerDraftOption] '{Tower.name}' is not in the tower catalog; " +
                               $"cannot grant. Add it to TowerPlacementManager.towerDefinitions.");
                return false;
            }

            return deck.ServerGrantTower(typeId);
        }
    }
}
