<?php

declare(strict_types=1);

namespace App\Auth;

/**
 * The minimal projection of a logged-in user the UI keeps in the session.
 *
 * `source` is `oidc` for users who logged in via Microsoft Entra and
 * `local` for the local-admin path. The api is the source of truth for
 * the user record; this struct is only what the UI needs to render
 * top-nav, sidebar visibility, and the `/app/me` page.
 */
final class UserContext
{
    public const SOURCE_OIDC = 'oidc';
    public const SOURCE_LOCAL = 'local';

    public function __construct(
        public readonly int $userId,
        public readonly string $displayName,
        public readonly string $role,
        public readonly ?string $email,
        public readonly string $source,
    ) {
    }

    /**
     * @param array<string, mixed> $row
     */
    public static function fromArray(array $row): self
    {
        return new self(
            userId: (int) $row['user_id'],
            displayName: (string) ($row['display_name'] ?? ''),
            role: (string) ($row['role'] ?? 'viewer'),
            email: isset($row['email']) ? (string) $row['email'] : null,
            source: (string) ($row['source'] ?? self::SOURCE_OIDC),
        );
    }

    /**
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        return [
            'user_id' => $this->userId,
            'display_name' => $this->displayName,
            'role' => $this->role,
            'email' => $this->email,
            'source' => $this->source,
        ];
    }
}
