#include "ZMMOJobsLibrary.h"

#include "Engine/GameInstance.h"
#include "Engine/World.h"
#include "ZMMOJobDataAsset.h"
#include "ZMMOJobsSubsystem.h"
#include "ZeusNetworkSubsystem.h"

namespace
{
/// Resolve Subsystem via WorldContextObject. Retorna nullptr em contextos
/// invalidos (CDO em editor, world em destruicao).
UZMMOJobsSubsystem* ResolveSubsystem(const UObject* WorldContextObject)
{
	if (WorldContextObject == nullptr) { return nullptr; }
	const UWorld* World = WorldContextObject->GetWorld();
	if (World == nullptr) { return nullptr; }
	UGameInstance* GI = World->GetGameInstance();
	if (GI == nullptr) { return nullptr; }
	return GI->GetSubsystem<UZMMOJobsSubsystem>();
}
}  // namespace

FText UZMMOJobsLibrary::GetJobDisplayName(const UObject* WorldContextObject, int32 ClassId)
{
	if (UZMMOJobsSubsystem* Sub = ResolveSubsystem(WorldContextObject))
	{
		if (UZMMOJobDataAsset* Job = Sub->GetJobData(ClassId))
		{
			return Job->DisplayName.IsEmpty()
				? FText::FromString(Job->TechnicalName)
				: Job->DisplayName;
		}
	}
	// Fallback: nao crasha UI se ClassId desconhecido.
	return FText::FromString(FString::Printf(TEXT("Classe %d"), ClassId));
}

UZMMOJobDataAsset* UZMMOJobsLibrary::GetJobData(const UObject* WorldContextObject, int32 ClassId)
{
	if (UZMMOJobsSubsystem* Sub = ResolveSubsystem(WorldContextObject))
	{
		return Sub->GetJobData(ClassId);
	}
	return nullptr;
}

bool UZMMOJobsLibrary::IsJobRegistered(const UObject* WorldContextObject, int32 ClassId)
{
	if (UZMMOJobsSubsystem* Sub = ResolveSubsystem(WorldContextObject))
	{
		return Sub->GetJobData(ClassId) != nullptr;
	}
	return false;
}

TArray<UZMMOJobDataAsset*> UZMMOJobsLibrary::GetJobsByTier(
	const UObject* WorldContextObject, EZMMOJobTier Tier)
{
	if (UZMMOJobsSubsystem* Sub = ResolveSubsystem(WorldContextObject))
	{
		return Sub->GetJobsByTier(Tier);
	}
	return {};
}

TArray<UZMMOJobDataAsset*> UZMMOJobsLibrary::GetEligibleNextJobs(
	const UObject* WorldContextObject, int32 CurrentClassId)
{
	if (UZMMOJobsSubsystem* Sub = ResolveSubsystem(WorldContextObject))
	{
		return Sub->GetEligibleNextJobs(CurrentClassId);
	}
	return {};
}

void UZMMOJobsLibrary::SendJobChangeRequest(
	const UObject* WorldContextObject, int32 TargetClassId)
{
	if (WorldContextObject == nullptr) { return; }
	const UWorld* World = WorldContextObject->GetWorld();
	if (World == nullptr) { return; }
	UGameInstance* GI = World->GetGameInstance();
	if (GI == nullptr) { return; }
	if (UZeusNetworkSubsystem* Net = GI->GetSubsystem<UZeusNetworkSubsystem>())
	{
		Net->SendJobChangeRequest(TargetClassId);
	}
}
