<?php

namespace Lucent\Commands;

use Illuminate\Console\Command;
use Illuminate\Database\Schema\Blueprint;
use Lucent\Database\Database;

class Setup extends Command
{

    protected $signature = 'lucent:setup';

    protected $description = 'Setup a new lucent installation';


    public function handle()
    {
        $this->updateComposer();
        $this->call('vendor:publish', ['--tag' => 'lucent-config']);
        $this->call('vendor:publish', ['--tag' => 'lucent']);
        $this->database();
        $this->info("Head to /lucent in your browser to create the first user");

    }

    private function updateComposer()
    {

        if (!$this->confirm('Update composer.json?')) {
            return;
        }

        $composerFile = json_decode(file_get_contents(base_path("composer.json")), true);
        $postAutoloadDumpList = data_get($composerFile, "scripts.post-autoload-dump", []);

        if (in_array("@php artisan vendor:publish --tag=lucent --force", $postAutoloadDumpList)) {
            $this->info("Composer file was already correct");
            return;
        }

        $composerFile["scripts"]["post-autoload-dump"][] = "@php artisan vendor:publish --tag=lucent --force";
        file_put_contents(base_path("composer.json"), json_encode($composerFile, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        $this->info("Composer file was updated");

    }

    private function database(): void
    {
        $databaseConnectionName = config("lucent.database");
        if (!$this->confirm("Your current database connection is $databaseConnectionName. Running the database migration script will wipe off any existing data. Run?")) {
            return;
        }
        $this->call('lucent:setup-db');
    }


}
