<?php

namespace App\Modules\Network\Commands;

use Carbon\Carbon;
use Log;

use App\Modules\Network\Models\Networks;
use App\Modules\Network\Helpers\CoreroSSP;

use App\Modules\Network\Models\Mitigation\MitigationOrganisationAttributes;

class MitigationSspDelete extends \App\Console\Commands\BaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mitigation:ssp-delete';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Delete prefixes from the Corero SSP.';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $corero_ssp = new CoreroSSP(env('CORERO_SSP_ENDPOINT'), env('CORERO_SSP_API_VERSION'), env('CORERO_SSP_USERNAME'), env('CORERO_SSP_PASSWORD'));

        // Get all related organisation SSP identifiers
        $ssp_ids = NetworkOrganisationAttributes::select('ssp_id', 'organisation_id')->whereIn('organisation_id', $removable_networks->pluck('organisation_id'))->get()->keyBy('organisation_id');

        // Work out what could be deleted - Only select largest supernets, ergo those with no supernets above them.
        $removable = Prefixes::leftJoin('supernets', 'subnet_id', '=', 'prefixes.id')->select(DB::raw('count(*)'), 'address', 'mask')->where('seen_at', '<', Carbon::now()->subDays(30))->groupBy('prefixes.id')->having(DB::raw('count(*)'), '=', '1')->get();

        // Go over removable networks and then delete them from SSP.
        foreach($removable_networks as $removable) {
            if(isset($ssp_ids[$removable->organisation_id])) {
                // Remove from SSP
                if($ssp_ids[$removable->organisation_id]->ssp_id != 0) {
                    Log::debug('DELETE: ' . $ssp_ids[$removable->organisation_id]->ssp_id . ": $removable->address/$removable->mask");
                    $corero_ssp->delete_prefix($ssp_ids[$removable->organisation_id]->ssp_id, "$removable->address/$removable->mask");
                }
            }
        }

        return 0;
    }
}