<?php

namespace App\Console\Commands\Network;

use App\Console\Commands\BaseCommand;
use Illuminate\Support\Facades\DB;

use App\Models\Prefixes;
use Illuminate\Support\Facades\Log;
use Throwable;

class GeoIpSetup extends BaseCommand
{

    protected $signature = 'geoip:setup';

    protected $description = 'Sets up geolocation objects.';

    protected $notEnterprise = true;

    public function handle()
    {
        try {
            Prefixes::leftJoin('prefix_geo_ip', 'prefix_id', '=', 'prefixes.id')
                ->select('prefixes.id as relevant_id', DB::raw('prefix_geo_ip.id as geo_id'))
                ->whereIn('prefixes.organisation_id', [ 1, 8 ])
                ->where(function($x) {
                    $x->where(function($y) {
                        $y->whereNull('prefix_id')->whereNull('prefix_geo_ip.deleted_at');
                    })
                    ->orWhere(function($y) {
                        $y->where('setup_required', '=', 1);
                    });
                })
                ->chunk(config('creatia.constant.chunk_large'), function($prefix_chunk) {
                    
                    $insert_count = 0;

                    $to_insert = [];

                    foreach($prefix_chunk as $prefix) {

                        // Create geo entries where they presently don't exist

                        if($prefix->geo_id == null) {
                            ++$insert_count;
                            $to_insert[] = [
                                'prefix_id'         => $prefix->relevant_id,
                                'country'           => null,
                                'region'            => null,
                                'city'              => null,
                                'organisation_id'   => 1,
                                'whois_error'       => null
                            ];
                        }
                    }

                    DB::table('prefix_geo_ip')->insert($to_insert);

                    Log::debug("LOCUS/SETUP - Insert: $insert_count");
                });
                
        }
        catch(Throwable $ex) {}

        return 0;
    }
}