#pragma once

#include "CoreMinimal.h"
#include "WingServer.h"
#include "WingHandler.h"
#include "WingFetcher.h"
#include "WingProperty.h"
#include "WingUtils.h"
#include "Details_SetMany.generated.h"

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

public:
	UPROPERTY(EditAnywhere, meta=(Description="Target object"))
	FString Object;

	UPROPERTY(EditAnywhere, meta=(Description="Object mapping property names to new values in Unreal text format"))
	FWingJsonObject Properties;

	virtual void Register() override
	{
		UWingServer::AddHandler(this,
			TEXT("Set one or more editable properties. Values use Unreal text format."));
	}

	virtual void Handle() override
	{
		WingFetcher F;
		UObject* Obj = F.Walk(Object).Cast<UObject>();
		if (!Obj) return;

		if (!Properties.Json || Properties.Json->Values.Num() == 0)
		{
			UWingServer::Print(TEXT("Error: No properties specified\n"));
			return;
		}

		TArray<FWingProperty> Props = FWingProperty::GetDetailsMutable(Obj, CPF_Edit);

		// Validation pass — resolve all properties before modifying anything.
		for (const auto& Pair : Properties.Json->Values)
		{
			FWingProperty* P = WingUtils::FindOneWithExternalID(Pair.Key, Props, TEXT("Property"));
			if (!P) return;
		}

		// Assignment pass — store the values.
		int SuccessCount = 0;
		for (const auto& Pair : Properties.Json->Values)
		{
			FWingProperty* P = WingUtils::FindOneWithExternalID(Pair.Key, Props, TEXT("Property"));
			if (P->SetJson(Pair.Value)) SuccessCount++;
		}

		UWingServer::Printf(TEXT("Set %d/%d properties.\n"), SuccessCount, Properties.Json->Values.Num());
	}
};
