<?php

namespace App\Console\Commands\Network;

use App\Console\Commands\BaseCommand;
use Illuminate\Support\Facades\DB;

use App\Models\Prefixes;
use App\Models\Supernets;

use App\Models\Asns;

class AsnReconcile extends BaseCommand
{

    protected $signature = 'asn:reconcile';

    protected $description = 'Reconcile ownership of prefixes based upon their ASN - Cleans up supernets too..';

    public function handle()
    {

        // Iterate of each individual ASN and begin associating as needed, marking things as announced where possible.

        Asns::where('approved', '=', '1')->chunk(config('creatia.constant.chunk_large'), function($asns) {

            // Iterate over every individual ASN - Keeps things lighter if we do things per 
            foreach($asns as $asn) {
                DB::transaction(function() use($asn) {
                    // Get list of prefix identities to convert over the supernets later on...
                    $prefix_identities = Prefixes::where('asn_id', '=', $asn->id)->where('organisation_id', '!=', $asn->organisation_id)->select('id')->distinct()->get()->pluck('id');
                    
                    // Clean up mismatched prefixes - If owned by us and going to someone else, inherit everything. If owned by someone else, and going to someone else, require setup and deleted user subnets.
                    
                    // Owned by us
                    Prefixes::where('asn_id', '=', $asn->id)
                        ->where('organisation_id', '!=', $asn->organisation_id)
                        ->where('organisation_id', '=', 1)
                        ->update([
                            'organisation_id' => $asn->organisation_id,
                        ]);

                    // Reassociate ownership of subnets
                    Supernets::whereIn('subnet_id', $prefix_identities)->orWhereIn('supernet_id', $prefix_identities)
                        ->update([
                            'tenant_id' => $asn->organisation_id
                        ]);

                    return true;
                });
            }
        });
        
        return 0;
    }
}
