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

#include "NakedDesireGameMode.h"
#include "Kismet/GameplayStatics.h"
#include "NakedDesire/Clothing/ClothingItem.h"
#include "NakedDesire/Clothing/ClothingItemInstance.h"
#include "UObject/ConstructorHelpers.h"
#include "NakedDesire/Interactables/Wardrobe.h"
#include "NakedDesire/MissionBuilder/MissionsConfig.h"
#include "NakedDesire/MissionBuilder/MissionsManager.h"
#include "NakedDesire/Player/NakedDesireCharacter.h"

void ANakedDesireGameMode::RestartGame()
{
	UGameplayStatics::OpenLevel(this, "City");
}

AWardrobe* ANakedDesireGameMode::GetWardrobe() const
{
	return Wardrobe;
}

void ANakedDesireGameMode::BuyItem(UClothingItemInstance* ClothingItemInstance)
{
	ANakedDesireCharacter* Player = Cast<ANakedDesireCharacter>(UGameplayStatics::GetPlayerCharacter(GetWorld(), 0));
	if (!Player)
	{
		return;
	}

	if (Player->Money < ClothingItemInstance->GetClothingItem()->BasePrice)
	{
		return;
	}

	Player->Money -= ClothingItemInstance->GetClothingItem()->BasePrice;
	Wardrobe->ClothingItems.Add(ClothingItemInstance);
}

void ANakedDesireGameMode::OnHourChanged(int32 Hour)
{
	if (Hour == 4)
	{
		DaysPassed++;
		RefreshDailyMissions();
	}
}

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

	if (AActor* FoundActor = UGameplayStatics::GetActorOfClass(GetWorld(), AWardrobe::StaticClass()))
	{
		if (AWardrobe* WardrobeActor = Cast<AWardrobe>(FoundActor))
		{
			Wardrobe = WardrobeActor;
		}
	}
}

void ANakedDesireGameMode::RefreshDailyMissions()
{
	ANakedDesireCharacter* Player = Cast<ANakedDesireCharacter>(UGameplayStatics::GetPlayerCharacter(GetWorld(), 0));
	if (!Player)
	{
		return;
	}
	
	int ClampedIndex = FMath::Clamp(DaysPassed, 0, MissionsConfig->DailyMissions.Num() - 1);
	Player->MissionsManager->RefreshDailyMissions(MissionsConfig->DailyMissions[ClampedIndex].Missions);
}
