<?php

namespace App\Console\Commands\Network;

use App\Console\Commands\BaseCommand;
use App\Helpers\Utility\UtilPrefix;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

use App\Models\Prefixes;
use App\Models\PrefixInclusions;

class PrefixAnnounceV2 extends BaseCommand
{

    protected $signature = 'prefix:announce-v2';

    protected $description = 'Decides whether prefixes are still announced.';

    public function handle()
    {

        $announced_prefixes = collect([
            ...(UtilPrefix::get_detailed())->map(function($i) { return [ 'full' => $i->prefix ]; })->toArray(),
            ...(UtilPrefix::get_detailed_v6())->map(function($i) { return [ 'full' => $i->prefix ]; })->toArray(),
            ...PrefixInclusions::select(DB::raw("CONCAT(address,'/',mask) as full"))->get()->toArray()
        ])->keyBy('full');

        $known_prefixes = Prefixes::select('id', DB::raw('CONCAT(address, \'/\', mask) as prefix'))->get()->keyBy('prefix');

        $not_announced = [];
        $is_announced = [];

        foreach($known_prefixes as $x) {
            if(isset($announced_prefixes[$x->prefix])) {
                $is_announced[] = $x->id;
            }
            else {
                $not_announced[] = $x->id;
            }
        }

        $marked_as_announced = $marked_as_unannounced = 0;

        foreach(array_chunk($not_announced, 1000) as $x) {
            $marked_as_unannounced += Prefixes::whereIn('id', $x)->where('still_announced', '!=', 0)->update([
                'still_announced' => 0
            ]);
        }

        foreach(array_chunk($is_announced, 1000) as $x) {
            $marked_as_announced += Prefixes::whereIn('id', $x)->update([
                'seen_at' => Carbon::now(),
                'still_announced' => 1,
                'created_source' => 'prefix-list-uncrushed'
            ]);
        }

        \Log::info('Announcement status summary - Announced: ' . sizeof($is_announced) . ' (Marked: ' . $marked_as_announced . '), Unannounced: ' . sizeof($not_announced) . ' (Marked: ' . $marked_as_unannounced . ')');

        return 0;
    }
}
