<?php

namespace App\Console\Commands\Network;

use App\Console\Commands\BaseCommand;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class PrefixListImport extends BaseCommand
{
    
    protected $signature = 'prefix:list-import';

    protected $description = 'Import any prefixes that are not associated with known and approved ASNs';

    public function handle()
    {
        // We're going to do two things - Fetch the active lists, and store them. We'll only store them if they differ from the currently stored ones.
        $import_detailed = Http::get('http://' . config('creatia.endpoint.route_server') . '/api/routes/v4');
        $import_detailed_6 = Http::get('http://' . config('creatia.endpoint.route_server') . '/api/routes/v6');
        
        // Validate JSON for detailed entry
        $detailed_body = $import_detailed->body();
        $decoded_body = json_decode($detailed_body);

        if (json_last_error() !== JSON_ERROR_NONE) {
            Log::error("Invalid JSON in detailed V4 routes: " . json_last_error_msg());
            return 1;
        }

        $detailed_6_body = $import_detailed_6->body();
        $decoded_6_body = json_decode($detailed_6_body);

        if (json_last_error() !== JSON_ERROR_NONE) {
            Log::error("Invalid JSON in detailed V6 routes: " . json_last_error_msg());
            return 1;
        }

        if(sizeof($decoded_body) === 0) {
            Log::error("Size of imported V4 prefixes was zero.");
            return 1;
        }

        if(sizeof($decoded_6_body) === 0) {
            Log::error("Size of imported V6 prefixes was zero.");
            return 1;
        }
        
        $known_detailed = $known_detailed_6 = false;
        
        if(file_exists(storage_path('prefix.detailed.json'))) {
            $known_detailed = file_get_contents(storage_path('prefix.detailed.json'));
        }
        if(file_exists(storage_path('prefix.detailed6.json'))) {
            $known_detailed = file_get_contents(storage_path('prefix.detailed6.json'));
        }

        // We're reserving this just for a pretty logging message.
        $updated = [];

        if(md5($detailed_body) !== md5($known_detailed)) {
            $temp_file = storage_path('prefix.detailed.json.tmp');
            
            file_put_contents($temp_file, $detailed_body);
            rename($temp_file, storage_path('prefix.detailed.json'));
            
            $updated[] = 'Detailed-4';
        }

        if(md5($detailed_6_body) !== md5($known_detailed_6)) {
            $temp_file = storage_path('prefix.detailed6.json.tmp');
            
            file_put_contents($temp_file, $detailed_6_body);
            rename($temp_file, storage_path('prefix.detailed6.json'));
            
            $updated[] = 'Detailed-6';
        }
        
        if($updated !== []) {
            Log::info("Cached routes have changed for: " . implode(', ', $updated));
        }

        return 0;
    }
}