using UnityEngine;
using UnityEngine.Events;

/// <summary>
/// GAME 1303 Tier 7 — A box of stock the player can carry. Store Simulator.
///
/// SETUP
///  - Prefab: a box mesh + Collider + Rigidbody, on the "Carryable" layer, + this script.
///  - Product: which ProductType is inside. Units: how many are left in the box
///    (defaults to the product's Units Per Box on Start).
///  - Empty boxes: tick Destroy When Empty so used boxes vanish, or leave it off and let
///    the player carry them to a bin (a nice bit of busywork for a store sim).
/// </summary>
public class Carryable : MonoBehaviour
{
    public ProductType product;
    [Tooltip("-1 = use the product's Units Per Box.")]
    public int units = -1;
    public bool canBePickedUp = true;
    public bool destroyWhenEmpty = true;

    [Header("Events")]
    public UnityEvent OnPicked;
    public UnityEvent OnPut;
    public UnityEvent<int> OnUnitsChanged;
    public UnityEvent OnEmptied;

    public bool IsEmpty => units <= 0;
    public PickupCarry Holder { get; private set; }

    void Start()
    {
        if (units < 0) units = product != null ? product.unitsPerBox : 1;
        OnUnitsChanged?.Invoke(units);
    }

    public void OnPickedUp(PickupCarry by) { Holder = by; OnPicked?.Invoke(); }
    public void OnDropped()                { Holder = null; OnPut?.Invoke(); }

    /// <summary>Take one or more units out (ShelfSlot does this). Returns how many it got.</summary>
    public int TakeUnits(int amount)
    {
        int given = Mathf.Min(amount, units);
        units -= given;
        OnUnitsChanged?.Invoke(units);

        if (IsEmpty)
        {
            OnEmptied?.Invoke();
            if (destroyWhenEmpty)
            {
                if (Holder != null) Holder.ClearHeld();
                Destroy(gameObject);
            }
        }
        return given;
    }
}