// © 2025 Naked People Team. All Rights Reserved.


#include "MissionsManager.h"
#include "Mission.h"
#include "NakedDesire/Player/NakedDesireCharacter.h"


UMissionsManager::UMissionsManager()
{
	PrimaryComponentTick.bCanEverTick = false;
}

void UMissionsManager::BeginPlay()
{
	Super::BeginPlay();

	Player = Cast<ANakedDesireCharacter>(GetOwner());
	UE_LOG(LogTemp, Warning, TEXT("Player is NULL %s"), Player == nullptr ? TEXT("True") : TEXT("False"));

	for (const auto& Mission : AvailableMissions)
	{
		Mission->Init(Player);
		Mission->OnComplete.AddUObject(this, &UMissionsManager::CompleteMission);
	}
}

void UMissionsManager::CompleteMission(UMission* Mission)
{
	CompletedMissions.Add(Mission);
	AvailableMissions.Remove(Mission);
	OnMissionCompleted.Broadcast(Mission);
}

void UMissionsManager::CollectRewards()
{
	if (CompletedMissions.IsEmpty())
	{
		return;
	}
	
	int TotalReward = 0;
	for (const UMission* Mission : CompletedMissions)
	{
		TotalReward += Mission->GetMoneyReward();
	}

	Player->Money += TotalReward;
	CompletedMissions.Empty();
	OnRewardsCollected.Broadcast(TotalReward);
}

void UMissionsManager::RefreshDailyMissions(const TArray<UMission*>& NewMissions)
{
	for (UMission* Mission : AvailableMissions)
	{
		Mission->OnComplete.RemoveAll(this);
	}
	AvailableMissions.Reset();

	AvailableMissions.Append(NewMissions);

	for (UMission* Mission : AvailableMissions)
	{
		Mission->Init(Player);
		Mission->OnComplete.AddUObject(this, &UMissionsManager::CompleteMission);
	}
}

