<?php

namespace Tests\Unit;

use App\Support\EnvWriter;
use Illuminate\Support\Facades\File;
use Tests\TestCase;

class EnvWriterTest extends TestCase
{
    private string $tempDir;

    protected function setUp(): void
    {
        parent::setUp();

        $this->tempDir = sys_get_temp_dir().'/env-writer-test-'.uniqid('', true);
        File::makeDirectory($this->tempDir, 0755, true);
    }

    protected function tearDown(): void
    {
        if (File::isDirectory($this->tempDir)) {
            File::deleteDirectory($this->tempDir);
        }

        parent::tearDown();
    }

    public function test_prepare_for_installation_creates_env_without_example_file(): void
    {
        $envPath = $this->tempDir.'/.env';
        $writer = new EnvWriter($envPath);

        $writer->prepareForInstallation();

        $this->assertTrue(File::exists($envPath));

        $contents = File::get($envPath);
        $this->assertStringContainsString('APP_NAME=', $contents);
        $this->assertStringContainsString('APP_INSTALLED=false', $contents);
        $this->assertMatchesRegularExpression('/^APP_KEY=base64:[A-Za-z0-9+\/=]+$/m', $contents);
    }

    public function test_prepare_for_installation_generates_app_key_when_copied_example_is_empty(): void
    {
        $envPath = $this->tempDir.'/.env';
        $examplePath = $this->tempDir.'/.env.example';
        File::put($examplePath, "APP_NAME=Example\nAPP_KEY=\n");

        $writer = new EnvWriter($envPath);
        $writer->prepareForInstallation();

        $this->assertMatchesRegularExpression('/^APP_KEY=base64:[A-Za-z0-9+\/=]+$/m', File::get($envPath));
    }

    public function test_set_many_creates_env_file_when_missing(): void
    {
        $envPath = $this->tempDir.'/.env';
        $writer = new EnvWriter($envPath);

        $writer->setMany([
            'DB_DATABASE' => 'fresh_install',
            'DB_USERNAME' => 'root',
        ]);

        $contents = File::get($envPath);
        $this->assertStringContainsString('DB_DATABASE=fresh_install', $contents);
        $this->assertStringContainsString('DB_USERNAME=root', $contents);
    }
}
