<?php

namespace App\Services\Install;

/**
 * Step 3. Tests a candidate DB connection WITHOUT touching CI4's configured
 * connection (that only exists after .env is written in Step 8) — uses a
 * raw mysqli connection so "Test Connection" works before any config file
 * changes.
 */
class DatabaseConnectionTester
{
    public function test(string $host, string $port, string $database, string $username, string $password): array
    {
        mysqli_report(MYSQLI_REPORT_OFF);

        $conn = @mysqli_connect($host, $username, $password, '', (int) $port);

        if (! $conn) {
            return ['success' => false, 'message' => 'Could not connect: ' . mysqli_connect_error()];
        }

        $dbExists = @mysqli_select_db($conn, $database);

        if (! $dbExists) {
            $created = @mysqli_query($conn, "CREATE DATABASE IF NOT EXISTS `{$database}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
            if (! $created) {
                mysqli_close($conn);
                return [
                    'success' => false,
                    'message' => "Connected to server, but database '{$database}' does not exist and this user lacks CREATE DATABASE privilege. Please create it manually first.",
                ];
            }
        }

        $version = mysqli_get_server_info($conn);
        mysqli_close($conn);

        return ['success' => true, 'message' => "Connected successfully. MySQL server version: {$version}"];
    }
}
