using JetBrains.Annotations;
using LLM.Editor.Helper;
using UnityEditor;
using UnityEngine;

namespace LLM.Editor.Commands
{
    [System.Serializable]
    public class DeleteGameObjectParams
    {
        public int targetIdentifier;
    }

    [UsedImplicitly]
    public class DeleteGameObjectCommand : ICommand
    {
        private readonly DeleteGameObjectParams _params;

        public DeleteGameObjectCommand(string jsonParams)
        {
            _params = jsonParams?.FromJson<DeleteGameObjectParams>();
        }

        public CommandOutcome Execute(Data.CommandContext context)
        {
            if (_params == null || _params.targetIdentifier == 0)
            {
                context.ErrorMessage = "Invalid parameters: targetIdentifier is required.";
                Debug.LogError($"[DeleteGameObjectCommand] {context.ErrorMessage}");
                return CommandOutcome.Error;
            }

            var targetObject = EditorUtility.InstanceIDToObject(_params.targetIdentifier);
            if (!targetObject)
            {
                context.ErrorMessage = $"Could not find GameObject with ID: {_params.targetIdentifier}";
                Debug.LogError($"[DeleteGameObjectCommand] {context.ErrorMessage}");
                return CommandOutcome.Error;
            }

            if (AssetDatabase.Contains(targetObject))
            {
                context.ErrorMessage = $"Safety check failed: Attempted to delete an asset, not a scene object. Path: {AssetDatabase.GetAssetPath(targetObject)}";
                Debug.LogError($"[DeleteGameObjectCommand] {context.ErrorMessage}");
                return CommandOutcome.Error;
            }

            Object.DestroyImmediate(targetObject);
            Debug.Log($"[DeleteGameObjectCommand] Deleted object with previous ID: {_params.targetIdentifier}");
            return CommandOutcome.Success;
        }
    }
}