<?php

namespace AuthStack\Driver\Model\U2F;

use Buckhill\U2F\U2FKey;
use function Buckhill\U2F\u2f;
use Illuminate\Database\Eloquent\Model;
use AuthStack\Driver\Model\SecurityKey;

class AuthChallenge extends Model
{
    protected $table = 'mfa_u2f_auth';
    protected $fillable = ['key_id', 'challenge', 'version', 'created_at', 'updated_at'];
    protected $challenge_array = null;
    public $timestamps = true;

    public static function fromKeyId($key_id)
    {
        /** @var  $sec_key SecurityKey */
        $sec_key = SecurityKey::findOrFail($key_id);

        $u2fkey = U2FKey::fromArray($sec_key->getSecurityKeyMetadata());

        $challenge = u2f()->authenticate()->challenge($u2fkey);

        $me = static::create([
            'key_id'    => $sec_key->key_id, // This is NOT equal to $key_id
            'challenge' => $challenge->getChallenge(),
            'version'   => $challenge->getVersion()
        ]);

        $me->setChallenge($challenge->toArray());

        return $me;
    }

    /**
     * @param array $challenge
     * @return $this
     */
    public function setChallenge(array $challenge)
    {
        $this->challenge_array = $challenge;

        return $this;
    }

    /**
     * @return array
     */
    public function getChallenge()
    {
        return $this->challenge_array;
    }
}