<?php

namespace Tests\Feature;

use App\DTOs\Installer\WizardStateData;
use App\Models\User;
use App\Services\Installer\InstallFinalizeAction;
use App\Services\Installer\InstallerDatabaseConfigurator;
use App\Support\InstallationState;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;
use Spatie\Permission\Models\Role;
use Tests\TestCase;

class InstallFinalizeActionTest extends TestCase
{
    private string $sqlitePath;

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

        $this->sqlitePath = database_path('finalize-test-'.uniqid('', true).'.sqlite');
        touch($this->sqlitePath);
    }

    protected function tearDown(): void
    {
        if (isset($this->sqlitePath) && File::exists($this->sqlitePath)) {
            File::delete($this->sqlitePath);
        }

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

        parent::tearDown();
    }

    public function test_finalize_writes_env_migrates_and_creates_admin(): void
    {
        $state = new WizardStateData(
            appName: 'Finalize Test',
            appUrl: 'http://localhost',
            requirementsPassed: true,
            dbConnection: 'sqlite',
            dbDatabase: $this->sqlitePath,
            mailMailer: 'log',
            mailFromAddress: 'admin@example.com',
            mailFromName: 'Finalize Test',
            companyName: 'Test Co',
            companyEmail: 'co@example.com',
            timezone: 'UTC',
            locale: 'en',
            adminName: 'Super Admin',
            adminEmail: 'finalize@example.com',
            adminPhone: '9954770099',
            adminPassword: 'secure-password',
            licenseKey: 'TEST-LICENSE',
            installationId: 'test-installation-id',
            activationToken: 'test-token',
            apiSecret: 'test-secret',
            migrationsRun: true,
        );

        app(InstallerDatabaseConfigurator::class)->apply($state);
        Artisan::call('migrate', ['--force' => true]);

        app(InstallFinalizeAction::class)->execute($state);

        $envContents = File::get($this->tempEnvPath);
        $this->assertStringContainsString('APP_INSTALLED=true', $envContents);
        $this->assertStringContainsString('LICENSE_KEY=TEST-LICENSE', $envContents);

        $this->assertTrue(app(InstallationState::class)->isInstalled());

        $user = User::query()->where('email', 'finalize@example.com')->first();
        $this->assertNotNull($user);
        $this->assertSame('9954770099', $user->phone);
        $this->assertTrue(Role::where('name', 'Super Admin')->exists());
        $this->assertTrue($user->hasRole('Super Admin'));
    }
}
