<?php

declare(strict_types=1);

namespace App\ApiClient\DTOs;

/**
 * Mirrors the api's user-shape (`{user_id, role, email, display_name, is_local}`)
 * returned by `/api/v1/auth/users/upsert-{oidc,local}` and `/api/v1/admin/me`.
 */
final class UserDto
{
    public function __construct(
        public readonly int $userId,
        public readonly string $role,
        public readonly ?string $email,
        public readonly string $displayName,
        public readonly bool $isLocal,
        public readonly ?string $source = null,
    ) {
    }

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

    public function effectiveSource(): string
    {
        return $this->source ?? ($this->isLocal ? 'local' : 'oidc');
    }
}
