<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;

class PrepareTestingDatabases extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'testing:prepare-databases';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Build template master and tenant SQLite databases.';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $base = base_path('database/testing');

        if (!is_dir($base) && !mkdir($base)) {
            throw new \RuntimeException(sprintf('Directory "%s" was not created', $base));
        }

        // Remove ALL previous test db files in this folder
        foreach (glob($base . '/*') as $file) {
            if (is_file($file)) {
                @unlink($file);
            }
        }

        $this->prepareDatabase('master', $base);
        $this->prepareDatabase('tenant', $base);

        return Command::SUCCESS;
    }

    private function prepareDatabase(string $type, string $base): void
    {
        $connection = "{$type}-test";
        $templateFile = $base . "/{$type}-template.sqlite";
        $schemaPath = database_path("schema/test-{$type}-schema.sql");
        $migrationPath = $type === 'master'
            ? database_path('migrations')
            : database_path('migrations/tenant');

        if (!file_exists($schemaPath)) {
            $this->error("Schema not found at: $schemaPath");
            return;
        }

        config()->set("database.connections.{$connection}", [
            'driver' => 'sqlite',
            'database' => ':memory:',
            'foreign_key_constraints' => true,
        ]);

        Config::set('database.default', $connection);

        if ($type === 'master') {
            Config::set('tenancy.database.central_connection', $connection);
        }

        Artisan::call('migrate', [
            '--database' => $connection,
            '--schema-path' => $schemaPath,
            '--path' => $migrationPath,
            '--realpath' => true,
            '--force' => true,
        ]);

        DB::connection($connection)->getPdo()->exec("VACUUM INTO '$templateFile'");

        $this->info(ucfirst($type) . " template created: $templateFile");
    }
}
