<?php

namespace Tests;

use App\Contracts\ProductOwnerClientContract;
use App\Services\ProductOwner\Drivers\MockProductOwnerDriver;
use App\Support\EnvWriter;
use App\Support\InstallationState;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Support\Facades\File;

abstract class TestCase extends BaseTestCase
{
    protected ?string $tempEnvPath = null;

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

        $this->app->instance(ProductOwnerClientContract::class, new MockProductOwnerDriver);

        $this->tempEnvPath = sys_get_temp_dir().'/admin-test-'.uniqid('', true).'.env';
        File::put($this->tempEnvPath, 'APP_KEY=base64:'.base64_encode(random_bytes(32)).PHP_EOL);
        $this->app->instance(EnvWriter::class, new EnvWriter($this->tempEnvPath));

        $installationState = app(InstallationState::class);
        if (File::exists($installationState->lockPath())) {
            File::delete($installationState->lockPath());
        }

        $wizardPath = storage_path('app/'.config('installer.wizard_state_file', 'installer/wizard.dat'));
        if (File::exists($wizardPath)) {
            File::delete($wizardPath);
        }
    }

    protected function tearDown(): void
    {
        if ($this->tempEnvPath !== null && File::exists($this->tempEnvPath)) {
            File::delete($this->tempEnvPath);
        }

        parent::tearDown();
    }
}
