<?php

declare(strict_types=1);

namespace PhpWA\Crypto\Signal;

final class SignalSessionRecord
{
    public const ARCHIVED_LIMIT = 6;

    /** @var list<SignalSession> */ private $sessions;

    /** @param list<SignalSession> $sessions */
    public function __construct(array $sessions = [])
    {
        if (count($sessions) > self::ARCHIVED_LIMIT + 1) {
            throw new \InvalidArgumentException('Signal session record contains too many sessions.');
        }
        foreach ($sessions as $session) {
            if (!$session instanceof SignalSession) { throw new \InvalidArgumentException('Signal session record is invalid.'); }
        }
        $this->sessions = array_values($sessions);
    }

    /** @return list<SignalSession> */ public function sessions(): array { return $this->sessions; }
    public function isEmpty(): bool { return $this->sessions === []; }
    public function openSession(): ?SignalSession { foreach ($this->sessions as $session) { if ($session->index()->closed() === -1) { return $session; } } return null; }
    public function sessionByBaseKey(string $baseKey): ?SignalSession { foreach ($this->sessions as $session) { if (hash_equals($session->index()->baseKey(), $baseKey)) { return $session; } } return null; }
    public function prepend(SignalSession $session): void { array_unshift($this->sessions, $session); $this->trim(); }
    public function closeOpenSession(): void { $open = $this->openSession(); if ($open !== null) { $open->index()->close(); } }
    public function trim(): void { if (count($this->sessions) > self::ARCHIVED_LIMIT + 1) { $this->sessions = array_slice($this->sessions, 0, self::ARCHIVED_LIMIT + 1); } }
}
