<?php

namespace AuthStack\TwoFactor\Model\U2F;

use function Buckhill\u2f\u2f;
use AuthStack\TwoFactor\Model\MFAMode;
use Illuminate\Database\Eloquent\Model;
use Buckhill\U2F\Exceptions\ChallengeMismatchException;

class Enrollment extends Model
{
    protected $table = 'mfa_u2f_enroll';
    public $timestamps = true;
    protected $fillable = ['challenge', 'version', 'app_id', 'title', 'created_at', 'updated_at'];

    /**
     * @param $app_id
     * @param $title
     * @return array
     */
    public static function enroll($app_id, $title)
    {
        $challenge = u2f()->enroll()->challenge($app_id);

        $model = static::create([
            'challenge' => $challenge['challenge'],
            'version'   => $challenge['version'],
            'app_id'    => $challenge['appId'],
            'title'     => $title
        ]);

        return [
            'challenge_id'      => $model->id,
            'challenge'         => $model->challenge,
            'version'           => $model->version,
            'appId'             => $model->app_id,
            'title'             => $model->title
        ];
    }

    /**
     * @param $challenge_id
     * @param array $data
     * @return array
     * @throws ChallengeMismatchException
     */
    public static function register($challenge_id, array $data)
    {
        $enroll     = static::findOrFail($challenge_id);
        $response   = u2f()->enroll()->response($data);
        $challenge  = isset($data['challenge']) ? $data['challenge'] : '';

        if(0 !== strcmp($enroll->challenge, $challenge))
        {
            throw new ChallengeMismatchException("Challenge mismatch");
        }

        $response
            ->parse()
            ->verifySignature()
        ;

        $enroll->delete();

        return [
            'mode_id'       => MFAMode::MODE_U2F,
            'title'         => $enroll->title,
            'metadata'      => $response->toArray()
        ];
    }
}