<?php
 
namespace App\Rules;
 
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Http;

class Bpf implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        if(config('app.env') === 'development' || config('app.env') === 'testing') {
            return true;
        }

        $hmac = hash_hmac('sha256', "$value", config('creatia.secret.bgp_forward')); 

        try {
            $result = Http::withHeaders([
                    'Authorization' => "$hmac",
                    'Content-Type' => 'application/json'
                ])
                ->retry(3, 100)
                ->timeout(15)
                ->get(config('creatia.endpoint.bgp_forward') . '/bpf', [ 'rule' => $value ])
                ->status();

            if($result == 200) {
                return true;
            }
        }
        catch(\Exception $ex) {
            \Log::debug($ex);
        }

        return false;
    }
 
    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be a valid BPF.';
    }
}