<?php

namespace Tests\Feature;

use App\Contracts\InstalledModuleRepositoryContract;
use App\Enums\ModuleStatus;
use App\Services\Installer\WizardSessionStore;
use App\Support\EnvWriter;
use App\Support\InstallationState;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\File;
use Tests\TestCase;

class ResetInstallationCommandTest extends TestCase
{
    use RefreshDatabase;
    public function test_install_reset_clears_lock_wizard_state_and_env_flag(): void
    {
        app(InstallationState::class)->markInstalled();
        app(WizardSessionStore::class)->merge(['app_name' => 'Test Admin']);

        $this->artisan('install:reset', ['--force' => true])
            ->assertSuccessful()
            ->expectsOutputToContain('Installation reset');

        $this->assertFalse(app(InstallationState::class)->isInstalled());
        $this->assertFalse(File::exists(storage_path('app/'.config('installer.wizard_state_file', 'installer/wizard.dat'))));

        $envContents = File::get($this->tempEnvPath);
        $this->assertStringContainsString('APP_INSTALLED=false', $envContents);
    }

    public function test_install_reset_without_lock_still_clears_env_flag(): void
    {
        app(EnvWriter::class)->set('APP_INSTALLED', 'true');

        $this->artisan('install:reset', ['--force' => true])
            ->assertSuccessful()
            ->expectsOutputToContain('Installer state cleared');

        $this->assertStringContainsString('APP_INSTALLED=false', File::get($this->tempEnvPath));
    }

    public function test_install_reset_uninstalls_marketplace_modules(): void
    {
        app(InstallationState::class)->markInstalled();

        app(InstalledModuleRepositoryContract::class)->create([
            'module_uuid' => 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
            'name' => 'Finance',
            'version' => '1.0.0',
            'status' => ModuleStatus::Installed,
            'installed_at' => now(),
        ]);

        $this->artisan('install:reset', ['--force' => true])
            ->assertSuccessful()
            ->expectsOutputToContain('Uninstalled 1 marketplace module(s).');

        $this->assertDatabaseCount('installed_modules', 0);
    }
}
