<?php

namespace App\Console\Commands\Network;

use App\Console\Commands\BaseCommand;
use Illuminate\Support\Facades\DB;
use App\Helpers\Api\RADb;
use App\Helpers\Utility\UtilPrefix;
use App\Models\Asns;
use App\Models\AsSets;

class MercuryRADb extends BaseCommand
{

    protected $signature = 'mercury:radb';

    protected $description = 'Checks for a difference in the provisioned tunnels and RADb, and updates the AS-SET accordingly.';

    protected $notEnterprise = true;

    public function handle()
    {

        \Log::info("Checking RADb");

            // 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']);

                // Select all AS-SETs
                $valid_as_sets = AsSets::where('approved', '=', 1)
                    ->get()
                    ->pluck('as_set')
                    ->toArray();

                // Get the ASNs that have ever been associated with a tunnel.
                $valid_asns = Asns::where('approved', '=', 1)
                    ->select(DB::raw('CONCAT(\'AS\', asn) as x'))
                    ->whereNotIn('asn', ['2914', '15169', '3356', '64500', '64512', '65100', '327952'])
                    ->where('organisation_id', '!=', 1)
                    ->get()
                    ->pluck('x')
                    ->toArray();

                $valid_asns[] = 'AS137409';

                $member_entries = array_unique(array_merge($valid_asns, $valid_as_sets));

                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::info("Rewriting RADb");
                    \Log::debug($member_entries);
                    RADb::rewrite_as_set_members('AS137409:AS-MERCURY', $member_entries);   
                }
            }
            catch(\Exception $ex) {
                \Log::debug($ex);
            }
        
        return 0;
    }
}
