<?php

namespace App\Services\Installer;

class ServerRequirementsChecker
{
    /**
     * @return array{passed: bool, php_version: array, extensions: array<string, array>, writable_paths: array<string, array>}
     */
    public function check(): array
    {
        $minVersion = config('installer.php.min_version', '8.2.0');
        $phpPassed = version_compare(PHP_VERSION, $minVersion, '>=');

        $extensions = [];
        foreach (config('installer.php.extensions', []) as $extension) {
            $extensions[$extension] = [
                'required' => true,
                'passed' => extension_loaded($extension),
            ];
        }

        $writablePaths = [];
        foreach (config('installer.writable_paths', []) as $path) {
            $fullPath = base_path($path);
            $writablePaths[$path] = [
                'required' => true,
                'passed' => is_dir($fullPath) && is_writable($fullPath),
            ];
        }

        $extensionsPassed = collect($extensions)->every(fn (array $item) => $item['passed']);
        $pathsPassed = collect($writablePaths)->every(fn (array $item) => $item['passed']);

        return [
            'passed' => $phpPassed && $extensionsPassed && $pathsPassed,
            'php_version' => [
                'required' => $minVersion,
                'current' => PHP_VERSION,
                'passed' => $phpPassed,
            ],
            'extensions' => $extensions,
            'writable_paths' => $writablePaths,
        ];
    }
}
