<?php

require_once __DIR__ . '/../../src/Events/MonthEndEvent.php';

class HeatWaveHeatstrokeEvent extends MonthEndEvent
{
    public function getMinAge()
    {
        return 0;
    }

    public function getMinParticipants()
    {
        return 1;
    }

    public function getMaxParticipants()
    {
        return 3;
    }

    public function getCost()
    {
        return 35;
    }

    public function isAvailable()
    {
        if (empty($this->tribe->dataStore->heatWaveActive) || $this->tribe->dataStore->heatWaveActive <= 0) {
            return false;
        }

        $eligible = array_filter($this->tribe->getKobolds(), function ($kobold) {
            foreach ($kobold->getInjuries() as $injury) {
                if (($injury['id'] ?? null) === 'heatstroke') {
                    return false;
                }
            }
            return $kobold->getAge() >= $this->getMinAge();
        });

        return !empty($eligible);
    }

    public function execute()
    {
        $eligible = array_values(array_filter($this->tribe->getKobolds(), function ($kobold) {
            foreach ($kobold->getInjuries() as $injury) {
                if (($injury['id'] ?? null) === 'heatstroke') {
                    return false;
                }
            }
            return $kobold->getAge() >= $this->getMinAge();
        }));

        if (empty($eligible)) {
            return;
        }

        shuffle($eligible);
        $count = rand($this->getMinParticipants(), min($this->getMaxParticipants(), count($eligible)));
        $targets = array_slice($eligible, 0, $count);

        foreach ($targets as $kobold) {
            $kobold->addInjury('heatstroke');
            $kobold->save();
        }

        $names = implode(', ', array_map(fn($k) => $k->getName(), $targets));
        $variations = [
            "The heat wave proved too much for {$names}, who suffered heatstroke.",
            "Under the relentless sun, {$names} collapsed with heatstroke.",
            "The scorching days left {$names} with heatstroke by the month's end."
        ];

        $this->story = $variations[array_rand($variations)];
    }
}
