<?php

declare(strict_types=1);

namespace Ekdos\Users;

final readonly class User
{
    public function __construct(
        public string $id,
        public string $username,
        public string $displayName,
        public Role $role,
        public bool $isActive,
        public string $createdAt,
        public ?string $lastLoginAt = null,
        public string $passwordHash = '',
    ) {}

    public static function fromRow(array $row): self
    {
        return new self(
            id: (string) $row['id'],
            username: (string) $row['username'],
            displayName: (string) $row['display_name'],
            role: Role::from((string) $row['role']),
            isActive: (bool) $row['is_active'],
            createdAt: (string) $row['created_at'],
            lastLoginAt: isset($row['last_login_at']) ? (string) $row['last_login_at'] : null,
            passwordHash: (string) ($row['password_hash'] ?? ''),
        );
    }

    /** Die Form, die die Oberflaeche sieht. Der Hash verlaesst den Server nie. */
    public function toArray(): array
    {
        return [
            'id' => $this->id,
            'username' => $this->username,
            'displayName' => $this->displayName,
            'role' => $this->role->value,
            'roleLabel' => $this->role->label(),
            'isActive' => $this->isActive,
            'createdAt' => $this->createdAt,
            'lastLoginAt' => $this->lastLoginAt,
            'permissions' => $this->role->permissions(),
        ];
    }

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