<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\Organisation;
use App\Traits\Owned;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class AsSets extends Model
{
    use SoftDeletes;
    use Owned;

    protected $fillable = [
        'as_set',
        'approved',
        'organisation_id'
    ];

    /**
     * Notes: Unlike the ASN make function, AS-SETs do not require us to handle reassociation because nothing we import hinges on them like with ASNs.
     * Instead users will simply specify their AS-SET, and that is that. Only admins should be able to force a transfer via the bypass flag. 
     */
    public static function make($_as_set, $_organisation_id, $_admin_bypass = false) {

        Log::info("Attempting to add AS-SET $_as_set to Organisation #$_organisation_id - Admin bypass? $_admin_bypass");
        
        if(Organisation::find($_organisation_id)) {

            // Whether AS-SET already exists.
            $exists = AsSets::where('as_set', '=', strtoupper($_as_set))->first() ?? false;

            // Whether AS-SET exists in a given ASN
            $valid_nested_asn = false;
            $nested_asn = str_contains($_as_set, ':') ? explode(':', $_as_set) : false;

            if($nested_asn) {
                $valid_nested_asn = Asns::where([['organisation_id', '=', Auth::user()->organisation_id], ['asn', '=', ltrim($nested_asn[0], 'ASas')], ['approved', '=', 1]])->count();
            }

            Log::debug("AS-SET $_as_set valid and nested? $valid_nested_asn");

            if($_admin_bypass || $valid_nested_asn) {

                if($exists) {
                    AsSets::where('as_set', '=', strtoupper($_as_set))->update([
                        'approved'          => 1,
                        'organisation_id'   => $_organisation_id
                    ]);

                    Log::debug("Updated AS-SET");
                }
                else {
                    AsSets::create([
                        'as_set'            => strtoupper($_as_set),
                        'approved'          => 1,
                        'organisation_id'   => $_organisation_id
                    ]);

                    Log::debug("Created AS-SET");
                }

                return true;
            }
        }

        return false;
    }

}
