<?php

namespace App\Modules\Shared\Domain\Data;

class DataMap
{
    public array $map;

    public function __construct(
        array $data,
        callable | string  $key
    ) {
        $this->map = array_reduce(
            $data,
            function (array $carry, $item) use ($key) {
                $realKey = is_string($key) ? $item->{$key} : $key($item);
                $carry[$realKey] = $item;
                return $carry;
            },
            []
        );
    }

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

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

    public function remove(string $key): void
    {
        if (isset($this->map[$key])) {
            unset($this->map[$key]);
        }
    }

    public function exists(string $key): bool
    {
        return array_key_exists($key, $this->map);
    }
}
