<?php

namespace App\Services\Installer;

use Illuminate\Support\Facades\File;

class EnvFileEditor
{
    /**
     * @param  array<string, mixed>  $pairs
     */
    public function set(array $pairs): void
    {
        $envPath = base_path('.env');

        if (! File::exists($envPath)) {
            File::copy(base_path('.env.example'), $envPath);
        }

        $content = (string) File::get($envPath);

        foreach ($pairs as $key => $value) {
            $line = $key.'='.$this->formatValue($value);
            $pattern = '/^'.preg_quote($key, '/').'=.*$/m';

            if (preg_match($pattern, $content) === 1) {
                $content = (string) preg_replace($pattern, $line, $content);
                continue;
            }

            $suffix = str_ends_with($content, PHP_EOL) ? '' : PHP_EOL;
            $content .= $suffix.$line.PHP_EOL;
        }

        File::put($envPath, $content);
    }

    private function formatValue(mixed $value): string
    {
        if (is_bool($value)) {
            return $value ? 'true' : 'false';
        }

        if (is_null($value)) {
            return '';
        }

        if (is_numeric($value)) {
            return (string) $value;
        }

        $string = trim((string) $value);

        if ($string === '') {
            return '""';
        }

        $needsQuotes = preg_match('/\s|#|"|=/', $string) === 1;

        if (! $needsQuotes) {
            return $string;
        }

        $escaped = str_replace('"', '\"', $string);

        return '"'.$escaped.'"';
    }
}
