<?php

namespace App\Modules\Network\Commands;

use Illuminate\Support\Facades\DB;
use App\Helpers\Api\RADb;
use App\Modules\Network\Models\Mercury\MercuryTunnel;

class MercuryRADb extends \App\Console\Commands\BaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mercury:radb';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Checks for a difference in the provisioned tunnels and RADb, and updates the AS-SET accordingly.';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        if(env('MASTER') == 1) {
            // This should only be executed in the event that this copy of the system is running as the master instance.
            try
            {
                // Get the members of the AS-SET for this system.
                $members = array_unique(RADb::get_as_set_attributes('AS137409:AS-MERCURY')['members']);

                //$custom_as_sets = CustomAsSet::where('approved', '=', '1')->pluck('name')->toArray();
                //$custom_as_sets = array_unique($custom_as_sets);

                // Get the ASNs for active tunnels in our system.
                $valid_asns = MercuryTunnel::select(DB::raw('CONCAT(\'AS\', asn) as x'))
                    /*->where([
                        ['tunnel_state', '=', 'VERIFIED'],
                        ['bgp_state', '=', 'VERIFIED']
                    ])*/
                    ->leftJoin('asns', 'asn_id', '=', 'asns.id')
                    ->get()
                    ->pluck('x')
                    ->toArray();

                $valid_asns[] = 'AS137409';
                $valid_asns = array_unique($valid_asns);

                $member_entries = array_merge($valid_asns, []);

                sort($member_entries);
                sort($members);

                // Only bother updating RADb where it's necessary.
                if(count(array_diff(array_unique($member_entries), array_unique($members))) || count(array_diff(array_unique($members), array_unique($member_entries)))) {    
                    \Log::debug("Rewriting RADb");
                    RADb::rewrite_as_set_members('AS137409:AS-MERCURY', $member_entries);   
                }
            }
            catch(\Exception $ex) {}
        }
        
        return 0;
    }
}
