<?php

declare(strict_types=1);

namespace PpPhp\Core\Platform\Identity;

final class PlatformIdGenerator
{
    private function __construct() {}

    public static function normalize(string $value): string
    {
        $value = strtolower(trim($value));
        $value = preg_replace('/[^a-z0-9_]+/', '_', $value) ?? '';
        $value = preg_replace('/_+/', '_', $value) ?? '';
        $value = trim($value, '_');

        if ($value === '') {
            return 'asset';
        }

        if (preg_match('/^[0-9]/', $value)) {
            $value = 'asset_' . $value;
        }

        return $value;
    }

    public static function uuid(string $prefix = 'asset'): string
    {
        return self::normalize($prefix) . '_' . bin2hex(random_bytes(4));
    }

    public static function unique(string $candidate, array $existingIds): string
    {
        $candidate = self::normalize($candidate);

        if (!in_array($candidate, $existingIds, true)) {
            return $candidate;
        }

        $i = 2;

        while (in_array($candidate . '_' . $i, $existingIds, true)) {
            $i++;
        }

        return $candidate . '_' . $i;
    }

    public static function isValid(string $id): bool
    {
        return (bool) preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $id);
    }
}
