<?php

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

class JealousItemEvent extends MonthEndEvent
{
    public function getMinAge()
    {
        return 10;
    }

    public function getMinParticipants()
    {
        return 2;
    }

    public function getMaxParticipants()
    {
        return 2;
    }

    public function getCost()
    {
        return 10;
    }

    public function isAvailable()
    {
        $eligible = array_filter($this->tribe->getKobolds(), function ($kobold) {
            return $kobold->getAge() >= $this->getMinAge();
        });

        if (count($eligible) < 2) {
            return false;
        }

        foreach ($eligible as $kobold) {
            $items = $kobold->getItems() ?? [];
            if (!empty($items)) {
                return true;
            }
        }

        return false;
    }

    private function ensureLikes($kobold)
    {
        if (!isset($kobold->dataStore)) {
            $kobold->dataStore = new stdClass();
        }
        if (!isset($kobold->dataStore->likes) || !is_array($kobold->dataStore->likes)) {
            $kobold->dataStore->likes = [];
        }
    }

    public function execute()
    {
        $kobolds = array_values($this->tribe->getKobolds());
        if (count($kobolds) < 2) {
            return;
        }

        $targets = array_values(array_filter($kobolds, function ($kobold) {
            $items = $kobold->getItems() ?? [];
            return !empty($items);
        }));

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

        $target = $targets[array_rand($targets)];
        $jealousOptions = array_values(array_filter($kobolds, fn($k) => $k->getId() !== $target->getId()));
        if (empty($jealousOptions)) {
            return;
        }

        $jealous = $jealousOptions[array_rand($jealousOptions)];
        $items = $target->getItems() ?? [];
        $item = $items[array_rand($items)];
        $itemName = is_array($item) ? ($item['name'] ?? $item['id'] ?? 'an item') : (is_object($item) && method_exists($item, 'getName') ? $item->getName() : 'an item');

        $this->ensureLikes($jealous);
        $current = $jealous->dataStore->likes[$target->getId()] ?? 0;
        $jealous->dataStore->likes[$target->getId()] = $current - 2;

        $variations = [
            "{$jealous->getName()} grew jealous of {$target->getName()}'s {$itemName}. The envy lingered, souring {$jealous->his()} opinion.",
            "Seeing {$target->getName()} with {$itemName} stirred jealousy in {$jealous->getName()}. {$jealous->his()} feelings toward {$target->getName()} cooled.",
            "{$jealous->getName()} fixated on {$target->getName()}'s {$itemName} and felt a sharp pang of envy, weakening the bond between them."
        ];

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