<?php

namespace App\Services\Documents;

class TokenScanner
{
    // Allow nested tokens like client.person.full_name or custom.order-id
    // Pattern: entity(.[subentity])* . attribute
    private const REGEX_DOUBLE = '/{{\s*([a-zA-Z0-9_]+(?:\.[a-zA-Z0-9_]+)*\.[a-zA-Z0-9_.-]+)\s*}}/';

    private const REGEX_SINGLE = '/\{\s*([a-zA-Z0-9_]+(?:\.[a-zA-Z0-9_]+)*\.[a-zA-Z0-9_.-]+)\s*\}/';

    /**
     * @return array<int,string>
     */
    public function scan(string $content): array
    {
        $out = [];
        if (preg_match_all(self::REGEX_DOUBLE, $content, $m1) && ! empty($m1[1])) {
            $out = array_merge($out, $m1[1]);
        }
        if (preg_match_all(self::REGEX_SINGLE, $content, $m2) && ! empty($m2[1])) {
            $out = array_merge($out, $m2[1]);
        }

        return array_values(array_unique($out));
    }
}
