#include "ZeusJobsLibrary.h"

#include "Engine/GameInstance.h"
#include "Engine/World.h"
#include "ZeusJobDataAsset.h"
#include "ZeusJobsSubsystem.h"
#include "ZeusNetworkSubsystem.h"

namespace
{
/// Resolve Subsystem via WorldContextObject. Retorna nullptr em contextos
/// invalidos (CDO em editor, world em destruicao).
UZeusJobsSubsystem* 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<UZeusJobsSubsystem>();
}
}  // namespace

FText UZeusJobsLibrary::GetJobDisplayName(const UObject* WorldContextObject, int32 ClassId)
{
	if (UZeusJobsSubsystem* Sub = ResolveSubsystem(WorldContextObject))
	{
		if (UZeusJobDataAsset* 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));
}

UZeusJobDataAsset* UZeusJobsLibrary::GetJobData(const UObject* WorldContextObject, int32 ClassId)
{
	if (UZeusJobsSubsystem* Sub = ResolveSubsystem(WorldContextObject))
	{
		return Sub->GetJobData(ClassId);
	}
	return nullptr;
}

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

TArray<UZeusJobDataAsset*> UZeusJobsLibrary::GetJobsByTier(
	const UObject* WorldContextObject, EZeusJobTier Tier)
{
	if (UZeusJobsSubsystem* Sub = ResolveSubsystem(WorldContextObject))
	{
		return Sub->GetJobsByTier(Tier);
	}
	return {};
}

TArray<UZeusJobDataAsset*> UZeusJobsLibrary::GetEligibleNextJobs(
	const UObject* WorldContextObject, int32 CurrentClassId)
{
	if (UZeusJobsSubsystem* Sub = ResolveSubsystem(WorldContextObject))
	{
		return Sub->GetEligibleNextJobs(CurrentClassId);
	}
	return {};
}

void UZeusJobsLibrary::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);
	}
}
