<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Mail\AsnApproval;
use App\Models\Organisation;
use App\Helpers\Utility\WhoIs;
use Illuminate\Support\Facades\Mail;

use Illuminate\Support\Str;

class Asns extends Model
{
    use SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'asn',
        'approved',
        'organisation_id',
        'email_token',
        'override_routelist'
    ];

    public static function adminRequest($_asn, $_organisation_id) {

    }

    public static function userRequest($_asn, $_email, $_organisation_id) {
        
    }

    public static function make($_asn, $_email, $_routelist, $_organisation_id, $_admin_bypass = false) {
        if(Organisation::find($_organisation_id)) {

            if($_admin_bypass) {
                Asns::create([
                    'asn' => ltrim($_asn, 'ASN'),
                    'approved' => 1,
                    'override_routelist' => $_routelist,
                    'email_token' => Str::random(128),
                    'organisation_id' => $_organisation_id
                ]);

                return true;
            }

            $email_list = WhoIs::asn_emails('AS' . ltrim($_asn, 'ASN')) ?? [];
    
            // Perform a who-is for the provided ASN, then check if the provided email is associated with the ASN who-is records.
            if(in_array($_email, $email_list)) {
                // Generate a token.
                $email_token = Str::random(32);
                        
                while(Asns::where('email_token', '=', $email_token)->count()) {
                    $email_token = Str::random(32);
                }
    
                // Create ASN object.
                Asns::create([
                    'asn' => ltrim($_asn, 'ASN'),
                    'approved' => 0,
                    'email_token' => $email_token,
                    'organisation_id' => $_organisation_id
                ]);

                // Send ASN approval email to the NOC.
                //Mail::to(env('APP_ENV') === 'development' ? config('security.development_email_direct') : $_email)->send(new AsnApproval($_asn, $email_token));
    
                // Redirect to dashboard
                return true;
            } else if(count($email_list) === 0) {
                return false;
            }
        }
        else {
            throw new Exception('No matching organisation found.');
        }
    }

}
