<?php

namespace App\Support;

use App\Models\Player;

/**
 * 玩家 SSO 首登自动建档时的默认展示名（username / nickname）。
 */
final class PlayerAutoRegistrationDefaults
{
    public const DISPLAY_NAME_PREFIX = 'nlotto';

    private const RANDOM_SUFFIX_DIGITS = 6;

    private const MAX_UNIQUE_ATTEMPTS = 10;

    public static function displayName(): string
    {
        for ($attempt = 0; $attempt < self::MAX_UNIQUE_ATTEMPTS; $attempt++) {
            $candidate = self::DISPLAY_NAME_PREFIX.self::randomSuffix();

            if (! Player::query()->where('username', $candidate)->exists()) {
                return $candidate;
            }
        }

        return self::DISPLAY_NAME_PREFIX.self::randomSuffix();
    }

    /**
     * @return array{username: string, nickname: string}
     */
    public static function profileFields(): array
    {
        $name = self::displayName();

        return [
            'username' => $name,
            'nickname' => $name,
        ];
    }

    private static function randomSuffix(): string
    {
        return str_pad((string) random_int(0, 999_999), self::RANDOM_SUFFIX_DIGITS, '0', STR_PAD_LEFT);
    }
}
