<?php

namespace App\Framework\Http\Session;

use App\Framework\Attributes\Singleton;
use App\Framework\DateTime\Clock;

final class Session
{
    private array $data = [];
    #private bool $isStarted = false;

    // Komponenten als Properties
    public readonly FlashBag $flash;
    public readonly ValidationErrorBag $validation;
    public readonly FormDataStorage $form;
    public readonly SecurityManager $security;
    public readonly CsrfProtection $csrf;

    public function __construct(
        public readonly SessionId $id,
        private readonly Clock $clock,
    ){
        #$this->isStarted = true;

        // Komponenten initialisieren
        $this->flash = new FlashBag($this);
        $this->validation = new ValidationErrorBag($this);
        $this->form = new FormDataStorage($this);
        $this->security = new SecurityManager($this, $this->clock);
        $this->csrf = new CsrfProtection($this);
    }

    public function isStarted(): bool
    {
        return true;
        #return $this->isStarted;
    }

    public function get(string $key, $default = null): mixed
    {
        return $this->data[$key] ?? $default;
    }

    public function set(string $key, $value): void
    {
        $this->data[$key] = $value;
    }

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

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

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

    public function clear(): void
    {
        $this->data = [];
    }

    public function fromArray(array $data): void
    {
        $this->data = $data;
    }

    public function __debugInfo(): array
    {
        return [$this->id->toString(), ...$this->data];
    }
}
