<?php

namespace App\Modules\Shared\Domain\Collection;

use ArrayAccess;
use ArrayIterator;
use Countable;
use IteratorAggregate;
use TypeError;

/**
 * @template T
 */
class GenericCollection implements Countable, ArrayAccess, IteratorAggregate
{

    private array $data;

    /** @param T ...$data */
    public function __construct(...$data)
    {
        $this->data = $data;
    }

    public function count(): int
    {
        return count($this->data);
    }

    public function data()
    {
        return $this->data;
    }

    public function getIterator(): ArrayIterator
    {
        return new ArrayIterator($this->data);
    }

    public function offsetExists(mixed $offset): bool
    {
        return isset($this->data[$offset]);
    }

    /**
     * @return T
     */
    public function offsetGet(mixed $offset)
    {
        return $this->data[$offset];
    }

    /**
     * @param T $value
     */
    public function offsetSet(mixed $offset, mixed $value): void
    {
        if ($value) {
            $this->data[$offset] = $value;
        } else throw new TypeError("Invalid value type");
    }

    public function offsetUnset(mixed $offset): void
    {
        unset($this->data[$offset]);
    }
}
