<?php

namespace App\Modules\JwtToken\Domain;

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

class JwtParams implements Countable, ArrayAccess, IteratorAggregate, Stringable
{

    private array $data;

    public function __construct(JwtParam ...$data)
    {
        $this->data = $data;
    }

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

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

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

    public function offsetGet(mixed $offset): JwtParam
    {
        return $this->data[$offset];
    }

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

    public function offsetUnset(mixed $offset): void
    {
        unset($this->data[$offset]);
    }
    
    public function __toString(): string
    {
        return implode('&', array_map(fn(JwtParam $param) => $param->key() . '=' . urlencode($param->value()), $this->data));
    }
}
