<?php

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

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

    public function getMinParticipants()
    {
        return 1;
    }

    public function getMaxParticipants()
    {
        return 3;
    }

    public function getCost()
    {
        return 30;
    }

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

        $eligible = array_filter($this->tribe->getKobolds(), function ($kobold) {
            foreach ($kobold->getInjuries() as $injury) {
                if (($injury['id'] ?? null) === 'dehydrated') {
                    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) === 'dehydrated') {
                    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('dehydrated');
            $kobold->save();
        }

        $names = implode(', ', array_map(fn($k) => $k->getName(), $targets));
        $variations = [
            "The drought wore on, and {$names} became dehydrated from the harsh conditions.",
            "With the dry air and sparse water, {$names} fell ill with dehydration.",
            "The drought took its toll; {$names} showed signs of dehydration by month's end."
        ];

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