<?php

namespace App\Console\Commands\Network;

use App\Console\Commands\BaseCommand;
use App\Models\GeoIp\PrefixGeoIp;
use App\Helpers\Utility\WhoIs;

class GeoIpSync extends BaseCommand
{

    protected $signature = 'geoip:sync';

    protected $description = 'Checks who-is status for each prefix.';

    protected $notEnterprise = true;

    public function handle()
    {
        PrefixGeoIp::leftJoin('prefixes', 'prefixes.id', '=', 'prefix_id')->select('address', 'mask', 'prefix_geo_ip.id', 'country')
            ->where([['prefixes.organisation_id', '=', 1], ['prefixes.asn_id', '=', 1]])
            ->whereNull('prefixes.deleted_at')
            ->whereNotNull('country')
            ->chunk(config('creatia.constant.chunk_medium'), function($x) {
                $to_null = [];
                $to_no_entry = [];
                $to_no_country = [];
                $to_not_aligned = [];

                foreach($x as $mod => $y) {
                    $who_is_raw = WhoIs::location_lookup("$y->address/$y->mask");

                    $who_is = ($who_is_raw == 'NO_ENTRY' || $who_is_raw == 'NO_COUNTRY') ? $who_is_raw : (array_search($y->country, $who_is_raw) ? null : 'NOT_ALIGNED'); 

                    switch($who_is) {
                        case 'NO_ENTRY':
                            $to_no_entry[] = $y->id;
                            break;
                        case 'NO_COUNTRY':
                            $to_no_country[] = $y->id;
                            break;
                        case 'NOT_ALIGNED':
                            $to_not_aligned[] = $y->id;
                            break;
                        default:
                            $to_null[] = $y->id;
                    }

                    // Sleep every five lookups, helps prevent rate limiting from kicking in.
                    if($mod % 5 === 0) {
                        sleep(2);
                    }
                }

                PrefixGeoIp::whereIn('id', $to_null)->update([ 'whois_error' => null ]);
                PrefixGeoIp::whereIn('id', $to_no_entry)->update([ 'whois_error' => 'NO_ENTRY' ]);
                PrefixGeoIp::whereIn('id', $to_no_country)->update([ 'whois_error' => 'NO_COUNTRY' ]);
                PrefixGeoIp::whereIn('id', $to_not_aligned)->update([ 'whois_error' => 'NOT_ALIGNED' ]);
        });

        
        return 0;
    }
}