<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Mtc\MercuryDataModels\Tenant;
use Stancl\Tenancy\Database\Models\Domain;

class SetTestDomain extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'set-test-domain';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Allows specifying which site should be set to the locahlost:3000 test domain';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        if (app()->environment('local') === false) {
            $this->error('This command is allowed only in local environment');
            return self::FAILURE;
        }
        $tenants = Tenant::query()->pluck('name', 'id')->toArray();
        $current = Domain::query()->where('domain', 'localhost:3000')->first()?->tenant_id;
        $choice = $this->choice(
            "Please select site which should be assigned the localhost:3000 domain",
            $tenants,
            $current
        );

        Domain::query()
            ->updateOrCreate([
                'domain' => 'localhost:3000'
            ], [
                'tenant_id' => $choice
            ]);
        $this->info('Domain updated');
        Cache::clear();
        return self::SUCCESS;
    }
}
