<?php

namespace Lucent\Setup\Step;

use Illuminate\Database\QueryException;
use Lucent\Database\Database;
use Lucent\Setup\Data\SetupStep;

class DatabaseSetupStep implements IStep
{

    public function __invoke(): SetupStep
    {


        $name = "Database Connection";

        $databaseConnectionName = config("lucent.database");


        $databaseConfig = config('database.connections.'.$databaseConnectionName);

        if (empty($databaseConfig)) {
            $instructions = <<<EOD
# You need to setup a database connection for $databaseConnectionName in database.php config. You can choose either sqlite or pgsql
# example:

'connections' => [
    '$databaseConnectionName' => [
        'driver' => 'sqlite',
        'url' => env('LUCENT_DATABASE_URL'),
        'database' => env('LUCENT_DB_DATABASE', database_path('database.sqlite')),
        'prefix' => '',
        'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
    ],
EOD;
            return SetupStep::makeFail($name, $instructions);
        }


        if(!in_array($driver = $databaseConfig["driver"],["sqlite","pgsql"])){
            $instructions = <<<EOD
You can choose either sqlite or pgsql. You current config is: $driver   
EOD;
            return SetupStep::makeFail($name, $instructions);
        }

        try {
            Database::make()->table("records")->get();
        } catch (QueryException $e) {
            $instructions = <<<EOD
# Make sure you run: 
php artisan lucent:setup-db
EOD;
            return SetupStep::makeFail($name, $instructions);
        }

        return SetupStep::makeSuccess($name, "Database Connection successfully created");
    }
}