<?php

namespace App\Console\Commands;

use App\Master\SiteManager;
use App\Tier;
use Database\Seeders\GlobalDatabaseSeed;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;
use Mtc\MercuryDataModels\Tenant;
use Vkovic\LaravelCommando\Handlers\Database\WithDbHandler;

class InstallLocalCommand extends Command
{
    use WithDbHandler;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'local:install';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Install System for local environment';

    /**
     * Create a new command instance.
     */
    public function __construct(protected SiteManager $siteManager)
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $seedDemoVehicles = $this->confirm('Do you want to seed demo vehicles?');

        $this->info('Checking if Global database is set-up...');
        $this->setUpGlobalDatabase();

        $this->setUpDatabase($seedDemoVehicles);

        return 0;
    }

    /**
     * Set up the global database by creating it, migrating, and seeding.
     */
    public function setUpGlobalDatabase(): void
    {
        $connection = Config::get('database.default');
        $database = Config::get("database.connections.$connection.database");

        $this->createDatabase($database);
        $this->migrateGlobalDatabase($database);
        $this->seedGlobalDatabase($database);
    }

    /**
     * Set up the tenant database by creating default tenants, seeding demo data,
     * and optionally seeding demo vehicles.
     *
     * @param bool $seedDemoVehicles
     */
    private function setUpDatabase(bool $seedDemoVehicles): void
    {
        Tenant::query()
            ->create([
                'name' => 'Small Dealership - Lite',
                'tier' => Tier::LITE->value,
            ])
            ->domains()->create([
                'domain' => str_replace(['http://', 'https://'], '', config('app.frontend_url')),
                'verified' => true,
            ]);

        Tenant::query()
            ->create([
                'name' => 'Medium Dealership - Standard',
                'tier' => Tier::STANDARD->value,
            ]);

        Tenant::query()
            ->create([
                'name' => 'Big Dealership - Pro',
                'tier' => Tier::PRO->value,
            ]);

        $this->info('Seeding Demo data');
        $this->call('tenants:run', [
            'commandname' => 'seed:theme'
        ]);

        if ($seedDemoVehicles) {
            $this->call('tenants:run', [
                'commandname' => 'seed:demo'
            ]);
        }

        $this->info('Indexing data for filter');
        $this->call('tenants:run', [
            'commandname' => 'filter:refresh-index'
        ]);
    }

    /**
     * Create the specified database if it does not exist.
     *
     * @param string $database
     */
    public function createDatabase(string $database): void
    {
        if ($this->dbHandler()->databaseExists($database) == false) {
            $this->dbHandler()->createDatabase($database);
            $this->output->success("Database `$database` created successfully");
        }
    }

    /**
     * Run the migrations for the global database.
     *
     * @param string $database
     */
    public function migrateGlobalDatabase(string $database): void
    {
        $this->call('migrate:fresh', [
            '--seed' => false,
            '--path' => 'vendor/mtcmedia/mercury-data-models/database/migrations',
        ]);
    }

    /**
     * Seed the global database with initial data.
     *
     * @param string $database
     */
    public function seedGlobalDatabase(string $database): void
    {
        $this->call('db:seed', [
            '--class' => GlobalDatabaseSeed::class,
        ]);
    }
}
