#pragma once

#include "CoreMinimal.h"
#include "WingServer.h"
#include "WingBasics.h"
#include "WingFetcher.h"
#include "Misc/PackageName.h"
#include "AssetToolsModule.h"
#include "IAssetTools.h"
#include "Asset_Rename.generated.h"


// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------

UCLASS()
class UWing_Asset_Rename : public UWingHandler
{
	GENERATED_BODY()

public:
	UPROPERTY(EditAnywhere, meta=(Description="Asset to rename"))
	FString Asset;

	UPROPERTY(EditAnywhere, meta=(Description="New package path or just a new name"))
	FString NewPath;

	virtual void Register() override
	{
		UWingServer::AddHandler(this,
			TEXT("Rename or move an asset with reference fixup."));
	}
	virtual void Handle() override
	{
		// Load the asset
		WingFetcher F(WingOut::Stdout);
		UObject* AssetObj = F.Asset(Asset).GetObj();
		if (!AssetObj) return;

		// Parse new path into package path and asset name
		FString NewPackagePath = FPackageName::GetLongPackagePath(NewPath);
		FString NewAssetName = FPackageName::GetShortName(NewPath);
		if (NewPackagePath.IsEmpty())
		{
			// No slash — just a new name, keep the same directory
			NewPackagePath = FPackageName::GetLongPackagePath(Asset);
			NewAssetName = NewPath;
			if (NewPackagePath.IsEmpty())
			{
				WingOut::Stdout.Printf(TEXT("ERROR: Cannot determine directory from Asset '%s'\n"), *Asset);
				return;
			}
		}

		// Perform the rename with reference fixup
		FAssetToolsModule& AssetToolsModule = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools");
		IAssetTools& AssetTools = AssetToolsModule.Get();

		TArray<FAssetRenameData> RenameData;
		RenameData.Add(FAssetRenameData(AssetObj, NewPackagePath, NewAssetName));

		if (!AssetTools.RenameAssets(RenameData))
		{
			WingOut::Stdout.Print(TEXT("ERROR: Rename failed. The target path may be invalid or a conflicting asset may exist.\n"));
			return;
		}

		WingOut::Stdout.Printf(TEXT("Renamed to %s/%s\n"), *NewPackagePath, *NewAssetName);
	}
};
