<?php

namespace App\Support;

use Symfony\Component\Process\ExecutableFinder;

/**
 * Resolves the Node.js executable for the Puppeteer scripts.
 *
 * PHP-FPM workers start with almost no PATH, and production installs Node
 * through nvm under another user's home, so a bare "node" is often not found.
 */
class NodeBinary
{
    public const SYSTEM_DIRECTORIES = ['/usr/local/bin', '/usr/bin', '/bin'];

    /**
     * @param  string|null  $configured  A per-feature binary; anything other than a bare "node" is used as given.
     * @param  list<string>  $searchDirectories  Searched in addition to PATH.
     */
    public static function resolve(?string $configured = null, array $searchDirectories = self::SYSTEM_DIRECTORIES): string
    {
        $configured = trim((string) $configured);

        if ($configured !== '' && $configured !== 'node') {
            return $configured;
        }

        $found = (new ExecutableFinder)->find('node', null, $searchDirectories);

        if ($found !== null) {
            return $found;
        }

        $fallback = trim((string) config('scraping.node_fallback_binary'));

        if ($fallback !== '' && is_executable($fallback)) {
            return $fallback;
        }

        return 'node';
    }
}
