<?php

namespace App\Models\Goliath;

use App\Models\Asns;
use App\Models\Organisation;
use App\Models\Prefixes;
use App\Notifications\SlackNotification;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Notification;

class PrefixGoliathInline extends Model
{
    use SoftDeletes;

    protected $table = 'prefix_goliath_inline';

    protected $fillable = [
        'prefix_id',
        'forced'
    ];

    private $changeLog = [];

    protected static function booted()
    {

        $change = function ($_m) {

            try {
                $new = $_m->getDirty();
                $old = $_m->getOriginal();
    
                $addr = Prefixes::find($_m->prefix_id);
    
                $user = Auth::user();
                $organisation = Organisation::find(Prefixes::find($_m->prefix_id)->organisation_id);
    
                $_m->changeLog = [
                    'Prefix' => "$addr->address/$addr->mask",
                    'User' => $user->name ?? 'AUTOMATION',
                    'Organisation' => "$organisation->name",
                    'Inline' => [
                        'Old' => $old === [] ? 'N/A' : ($old['forced'] != 1 ? 'On Detect' : 'Inline'),
                        'New' => $new === [] ? 'N/A' : (($new['forced'] ?? $old['forced']) != 1 ? 'On Detect' : 'Inline')
                    ],
                    'Asn' => Asns::find($addr->asn_id)->asn,
                    'Address' => "$addr->address"
                ];
            }
            catch (\Exception $ex) {
                \Log::error($ex);
            }

        };

        static::creating($change);
        static::updating($change);
        static::deleting($change);

        $done = function ($_m) {

            try {

                $notification = "Mitigation Inline Updated\n"
                    . 'Prefix: <https://bgp.tools/prefix/' . $_m->changeLog['Address'] . '|' . $_m->changeLog['Prefix'] . '> ( <https://bgp.tools/as/' . $_m->changeLog['Asn'] . '|AS' . $_m->changeLog['Asn'] . '>)' . "\n"
                    . 'User: ' . $_m->changeLog['User'] . "\n"
                    . 'Organisation: ' . $_m->changeLog['Organisation'] . "\n"
                    . 'Inline: ' . $_m->changeLog['Inline']['Old'] . ' -> ' . $_m->changeLog['Inline']['New'];


                $history = new GoliathHistory([
                    'type'              => GoliathHistoryType::Inline,
                    'history'           => json_encode($_m->changeLog),
                    'organisation_id'   => Prefixes::find($_m->prefix_id)->organisation_id,
                    'user_id'           => Auth::user()->id ?? null
                ]);
                
                $history->save();

                // Calculate who should see the history entries - People who are subtenanted specifically.
                $to_insert = [];

                foreach(Prefixes::find($_m->prefix_id)->getPrefixOrganisations() as $organisation) {
                    $to_insert[] = [ 'organisation_id' => $organisation, 'history_id' => $history->id ];
                }

                if($to_insert !== []) {
                    GoliathHistoryVisibility::insert($to_insert);
                }


                Notification::route('slack', config('creatia.webhook.goliath'))->notify(new SlackNotification($notification));
            }
            catch(\Exception $ex) {
                \Log::error($ex);

                try { \Log::info($notification); } catch (\Exception $i) {}
            }
        };

        static::created($done);
        static::updated($done);
        static::deleted($done);

    }
}
