using Mirror;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.InputSystem;

public class UnitMovement : NetworkBehaviour
{
    [SerializeField] private NavMeshAgent _navMeshAgent;

    private Camera _camera;
    private Mouse _mouse;

    #region Server

    [Command] private void CmdMove(Vector3 destination)
    {
        if (NavMesh.SamplePosition(destination, out NavMeshHit hit, 1f, NavMesh.AllAreas))
        {
            _navMeshAgent.SetDestination(hit.position);
        }
    }

    #endregion

    #region Client

    public override void OnStartAuthority()
    {
        base.OnStartAuthority();
        _camera = Camera.main;
        _mouse = Mouse.current;
    }

    [ClientCallback]
    private void Update()
    {
        if (!isOwned) return;
        if (!_mouse.rightButton.wasPressedThisFrame) return;
        Ray ray = _camera.ScreenPointToRay(_mouse.position.ReadValue());

        if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity))
        {
            CmdMove(hit.point);
        }
    }

    #endregion
}