<?php
declare(strict_types=1);

final class UserRepository {
    /** @return list<array{username:string,role:string}> */
    public static function listForAssignees(): array {
        $pdo = Database::pdo();
        $stmt = $pdo->query('SELECT username, role FROM users ORDER BY username ASC');
        $out = [];
        foreach ($stmt->fetchAll() as $row) {
            $out[] = [
                'username' => (string) $row['username'],
                'role' => (string) ($row['role'] ?? 'viewer'),
            ];
        }
        return $out;
    }

    /** @param list<string> $usernames */
    public static function validateUsernames(array $usernames): ?string {
        $want = [];
        foreach ($usernames as $u) {
            $u = trim((string) $u);
            if ($u !== '') {
                $want[strtolower($u)] = $u;
            }
        }
        if ($want === []) {
            return null;
        }
        $pdo = Database::pdo();
        $stmt = $pdo->query('SELECT username FROM users');
        $have = [];
        foreach ($stmt->fetchAll() as $row) {
            $have[strtolower((string) $row['username'])] = true;
        }
        foreach ($want as $lower => $orig) {
            if (!isset($have[$lower])) {
                return 'unknown user: ' . $orig;
            }
        }
        return null;
    }
}
