<?php

namespace App\Modules\Shared\Domain\Data;

class DataGroupMap
{
    private $dataMap;

    public function __construct(
        public array $data,
        callable | string $key
    ) {
        $this->generate($key);
    }

    private function generate(callable | string $key)
    {
        $this->dataMap = array_reduce(
            $this->data,
            function (array $carry, $item) use ($key) {
                $realKey = is_string($key) ? $item->{$key} : $key($item);
                if (!isset($carry[$realKey])) {
                    $carry[$realKey] = [];
                }
                $carry[$realKey][] = $item;
                return $carry;
            },
            []
        );
    }

    public function getObject(string $key)
    {
        return isset($this->dataMap[$key]) ? $this->dataMap[$key][0] : null;
    }

    public function get(string $key)
    {
        return isset($this->dataMap[$key]) ? $this->dataMap[$key] : null;
    }

    public function keys()
    {
        return array_keys($this->dataMap);
    }
}
