<?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()
    {
        // Remap database_path() to vendor package (mirrors AppServiceProvider::setMigrationLocation)
        $this->laravel->useDatabasePath(base_path('vendor/mtcmedia/mercury-data-models/database'));
        Config::set(
            'tenancy.migration_parameters.--path',
            base_path('vendor/mtcmedia/mercury-data-models/database/migrations/tenant')
        );

        $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");

        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);
        }

        $migrateOptions = [
            '--database' => $connection,
            '--force' => true,
        ];

        if ($type === 'master') {
            if (file_exists($schemaPath)) {
                $migrateOptions['--schema-path'] = $schemaPath;
            }
            $migrateOptions['--path'] = database_path('migrations');
            $migrateOptions['--realpath'] = true;
        } else {
            if (file_exists($schemaPath)) {
                $migrateOptions['--schema-path'] = $schemaPath;
            }
            // Only run tenant-specific migrations (central tables belong in master)
            $migrateOptions['--path'] = $this->getTenantMigrationPaths();
            $migrateOptions['--realpath'] = true;
        }

        Artisan::call('migrate', $migrateOptions);

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

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

    private function getTenantMigrationPaths(): array
    {
        return glob(base_path('vendor/mtcmedia/*/database/migrations/tenant'));
    }
}
