<?php

namespace Formatrica\Support;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Stable, immutable field identity.
 *
 * A field's `key` is generated once and never displayed or edited. It is the
 * identity backbone for conditional logic, drafts, calculations, and AI patch
 * application — features that must not break when an admin renames the editable
 * `name`. Treat the value as opaque: downstream code must use this generator
 * and validator rather than assuming the charset or token length.
 *
 * Format: `fld_` + 26 lowercase hex chars (13 random bytes).
 */
final class Field_Key
{
    private const PREFIX = 'fld_';

    /**
     * Generate a fresh opaque field key.
     */
    public static function generate(): string
    {
        return self::PREFIX . bin2hex(random_bytes(13));
    }

    /**
     * Whether a value is a well-formed field key produced by this generator.
     */
    public static function is_valid(mixed $key): bool
    {
        return is_string($key) && (bool) preg_match('/^fld_[0-9a-f]{26}$/', $key);
    }

    private function __construct()
    {
        // Static helper; not instantiable.
    }
}
