<?php

declare(strict_types=1);

namespace Ekdos\Auth;

use Ekdos\Users\Role;

/**
 * Der serverseitige Teil der Sitzung. Der Browser kennt davon nichts ausser
 * der undurchsichtigen Kennung im Cookie.
 */
final readonly class Session
{
    public function __construct(
        public string $id,
        public string $userId,
        public string $username,
        public string $displayName,
        public Role $role,
        public int $issuedAt,
        public int $lastSeenAt,
    ) {}

    public static function fromArray(string $id, array $data): ?self
    {
        $role = Role::tryFrom((string) ($data['role'] ?? ''));

        if ($role === null || !isset($data['userId'], $data['username'])) {
            return null;
        }

        return new self(
            id: $id,
            userId: (string) $data['userId'],
            username: (string) $data['username'],
            displayName: (string) ($data['displayName'] ?? $data['username']),
            role: $role,
            issuedAt: (int) ($data['issuedAt'] ?? 0),
            lastSeenAt: (int) ($data['lastSeenAt'] ?? 0),
        );
    }

    public function toArray(): array
    {
        return [
            'userId' => $this->userId,
            'username' => $this->username,
            'displayName' => $this->displayName,
            'role' => $this->role->value,
            'issuedAt' => $this->issuedAt,
            'lastSeenAt' => $this->lastSeenAt,
        ];
    }

    public function can(string $permission): bool
    {
        return $this->role->allows($permission);
    }
}
