<?php

namespace App\Services\Installer;

use App\DTOs\Installer\WizardStateData;
use Illuminate\Support\Facades\DB;

class InstallerDatabaseConfigurator
{
    public function apply(WizardStateData $state): void
    {
        if (empty($state->dbConnection)) {
            return;
        }

        config([
            'database.default' => $state->dbConnection,
            'database.connections.'.$state->dbConnection => array_merge(
                config('database.connections.'.$state->dbConnection, []),
                $this->connectionConfig($state)
            ),
        ]);

        DB::purge($state->dbConnection);
        DB::reconnect($state->dbConnection);
    }

    /**
     * @return array<string, mixed>
     */
    private function connectionConfig(WizardStateData $state): array
    {
        if ($state->dbConnection === 'sqlite') {
            return ['database' => $state->dbDatabase];
        }

        return [
            'host' => $state->dbHost,
            'port' => $state->dbPort,
            'database' => $state->dbDatabase,
            'username' => $state->dbUsername,
            'password' => $state->dbPassword,
        ];
    }
}
