<?php

namespace App\Modules\Network\Commands;

use Carbon\Carbon;
use App\Helpers\Utility\GoliathBgp;
use Illuminate\Support\Facades\DB;
use App\Modules\Network\Models\Prefixes;
use App\Models\Asns;

class GoliathWithdrawThread extends \App\Console\Commands\BaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'goliath:withdraw-thread {--as-max=} {--as-mod=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'For threading of withdrawals.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        try {

            // Things should always be handled in a small chunk of ASNs at any given one time to keep the load of prefixes being swapped at a time low...
            Asns::where('approved', '=', '1')
                ->where(DB::raw('id % ' . $this->option('as-max')), '=', $this->option('as-mod'))
                ->select('id')
                ->chunk(10, function($asns) {
                    
                GoliathBgp::emit_delta((
                    Prefixes::withTrashed()
                        ->whereRaw('family(address) = 4')
                        ->whereIn('asn_id', $asns->pluck('id'))
                        ->where('mask', '>=', 16)
                        ->where(function($x) {
                            $x->whereNull('setup_required')->orWhereNotIn('setup_required', [1, 2]);
                        })
                        ->where(function($x) {
                            $x->whereNull('prefixes.deleted_at')->orWhere('prefixes.deleted_at', '>', Carbon::now()->subMinutes(10));
                        })
                        ->select('prefixes.id')
                        ->get()
                        ->pluck('id')
                        ->toArray()
                ));
            });
        }
        catch(\Exception $ex) {
            \Log::debug($ex);
        }

        return 0;
    }
}