<?php

declare(strict_types=1);

namespace App\Framework\Http\Session;

use App\Framework\Http\IpAddress;

final readonly class SessionSecurityData
{
    public function __construct(
        public string $userAgent,
        public IpAddress $ipAddress,
        public int $lastActivity,
        public int $lastRegeneration
    ) {}

    public function withLastActivity(int $lastActivity): self
    {
        return new self(
            $this->userAgent,
            $this->ipAddress,
            $lastActivity,
            $this->lastRegeneration
        );
    }

    public function withLastRegeneration(int $lastRegeneration): self
    {
        return new self(
            $this->userAgent,
            $this->ipAddress,
            $this->lastActivity,
            $lastRegeneration
        );
    }

    public function toArray(): array
    {
        return [
            'user_agent' => $this->userAgent,
            'ip_address' => $this->ipAddress->value,
            'last_activity' => $this->lastActivity,
            'last_regeneration' => $this->lastRegeneration
        ];
    }

    public static function fromSession(Session $session): self
    {
        $data = $session->get(SessionKey::SECURITY->value);

        return new self(
            $data['user_agent'],
            new IpAddress($data['ip_address']),
            $data['last_activity'],
            $data['last_regeneration']
        );
    }
}
